JPython
本文 Python 版本 2.7
JPython pom
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
执行py脚本文件
在py脚本中直接定义的方法是OK的,但是调用 定义在类中的方法为nullPoint,后续继续研究……
import org.junit.Test;
import org.python.core.*;
import org.python.util.PythonInterpreter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
@Test
public void test3(){
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.execfile("xxx.py");
PyFunction func = (PyFunction) pythonInterpreter.get("add",PyFunction.class);
PyObject pyObject = func.__call__(new PyInteger(998),new PyInteger(1));
System.out.println(pyObject.toString());
}
def add(c, b):
return c+b
print(add(2, 3))
idea控制台输出print() 中内容
999
5
常见问题
- TypeError: object of type ‘NoneType’ has no len()
更新pom文件解决
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
java直接运行python代码
print注意Python 2.x 和 3.x 区别
@Test
public void test2(){
PythonInterpreter interpreter = new PythonInterpreter();
PySystemState sys = Py.getSystemState();
//指定python
sys.path.add("D:\\Program Files (x86)\\python32\\Lib");
interpreter.exec("print('hello')");
interpreter.exec("import sys");
interpreter.exec("print(sys.path)");
}
Runtime
@Test
public void testReadFromLocal() {
Process proc;
try {
proc = Runtime.getRuntime().exec("python D:\\ReturnTest.py");
//用输入输出流来截取结果
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line ;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
打开记事本 计算器
Runtime.getRuntime().exec("notepad.exe");
Runtime.getRuntime().exec("calc");
常见问题
Runtime.exec相当于在windows + R 中执行命令,确保python已经加入环境变量,否则请手动指定python环境
Runtime.getRuntime().exec("D:\\Program Files (x86)\\python32\\python.exe D:\\ReturnTest.py");
使用RunTime exec的风险请参考:
https://www.jianshu.com/p/af4b3264bc5d