JAVA调用Python
JAVA调用Python的方法:
- 通过 **PythonInterpreter.execfile() **方法实现;
- 通过 Runtime.getRuntime().exec(arg1) 方法实现;
使用第一种方法遇到的问题
解决方法
出现这个问题,查了很多资料都没有解决。最终换成了第二种方法解决。
完整代码
JAVA
Process pr;
try {
String[] args1 = new String[] { "python", "E:\\learn\\datacalculation.py", "10", "15"};
pr = Runtime.getRuntime().exec(args1);
BufferedReader in = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
/*try {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("E:\\learn\\datacalculation.py");
PyFunction pyFunction = interpreter.get("test", PyFunction.class);
int a = 5, b = 15;
PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("the anwser is: " + pyobj);
} catch (Exception e) {
e.printStackTrace();
}*/
Python
# coding=utf-8
import sympy as sp # 导入sympy包
x = sp.Symbol('x') # 定义符号变量
f = 0.137*x**-3 +0.119*x**-2 + 0.269*x**-1 - 0.019 - 44000/101300 # 定义要求解的一元三次方程
x = sp.solve(f) # 调用solve函数求解方程
#str(x) # solve函数的返回结果是一个列表
print('x' + str(x))