专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java调用Python脚本,以及报错解决

temp10 2024-09-22 10:08:41 java教程 14 ℃ 0 评论

极少数时候,我们会碰到类似这样的问题:与 A 同学合作写代码, A 同学只会写 Python,而不熟悉 Java,而你只会写 Java 并不擅长 Python,并且发现难以用 Java 来重写对方的代码,这时,就不得不想方设法“调用对方的代码”。下面举一些简单的小例子,借此说明:如何在 Java 中调用 Python 代码。

什么是 Jython?

Jython(原 JPython ),可以理解为一个由 Java 语言编写的 Python 解释器。

要使用 Jython, 只需要将 Jython-x.x.x.jar 文件置于 classpath 中即可 --> 官网下载,百度网盘。

Java调用Python脚本,以及报错解决

当然,通过 Maven 导入也 OK

<dependency>
 <groupId>org.python</groupId>
 <artifactId>jython-standalone</artifactId>
 <version>2.7.0</version></dependency>

一个 HelloPython 程序,在java中执行Python语句

import org.python.util.PythonInterpreter;

public class HelloPython {

public static void main(String[] args) {

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("print('hello')");

}

}

什么是 PythonInterpreter 呢?它的中文意思即“ Python 解释器”。我们知道 Python 程序都是通过解释器执行的,上面的代码就是在 JVM 中创建一个“ Python 解释器”对象,模拟 Python 解释器的行为,通过 exec(" Python 语句") 直接在 JVM 中执行 Python 代码,上面代码的输出结果为:hello,需要提醒各位的是,该程序运行速度相较正常的 Java or Python 程序都要慢那么一点。

在 JVM 中执行 Python 脚本

interpreter.execfile("D:/labs/mytest/hello.py");

如上,将 exec 改为 execfile 就可以了。需要注意的是,这个 .py 文件不能含有第三方模块,因为这个“ Python 脚本”最终还是在 JVM 环境下执行的(而非依赖于本地计算机环境),如果 .py 程序中有用到第三方模块(例如 NumPy)将会报错:java ImportError: No module named xxx

但是实际中,我们即使引入了Jytho-jar还是会报错

出现如下错误:

怎么解决呢?

在main方法中加入以下代码重构

Properties props = new Properties();
props.put("python.home", "path to the Lib folder");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);

把全部代码贴出来

package com.aidongsports.test;
import org.python.util.PythonInterpreter;
import java.util.Properties;
/**
* Created by HONGLINCHEN on 2017/12/11 11:15
* 测试java调用python
* @author HONGLINCHEN
* @since JDK 1.8
*/
public class TestPython {
public static void main(String[] args) {
Properties props = new Properties();
props.put("python.home", "path to the Lib folder");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
/*在 JVM 中执行 Python 语句*/
interpreter.exec("print('hello')");
/*在 JVM 中执行 Python 脚本,这个 .py 文件不能含有第三方模块*/
interpreter.execfile("E:\\TortoiseSVN\\trunk\\lovesports\\src\\main\\java\\com\\aidongsports\\test\\index.py");
}
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表