第一种:通过runtime
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("python3 /home/liudong/Documents/BPANN/test.py");
}catch (IOException e) {
e.printStackTrace();
}
第二种:通过jython(不传递参数,不依赖第三方模块)
PythonInterpreter interpreter =new PythonInterpreter();
interpreter.exec("print('hello')");//执行Python代码
interpreter.execfile("/home/liudong/Documents/BPANN/test.py");//执行python文件
第三种:调用需要传入参数的Python文件
PythonInterpreter interpreter =new PythonInterpreter();
interpreter.execfile("/home/liudong/Documents/BPANN/test.py");//要执行python文件
PyFunction function = interpreter.get("aa", PyFunction.class);//得到Python文件中的函数
//new PyString()代表传入的参数
PyObject pyObject = function.__call__(new PyString("jiajiajaijai"), new PyString("ddddddd"));
System.out.println("answer:: " + pyObject.toString());
对应的python文件为:
def aa(name, sex):
print("name: " + name)
print("sex: " + sex)
return name + sex
第四种:如何处理依赖了第三方模块的Python文件
本地文件下载相应的包,否则会一直报没有名为什么的模块。
通过命令行执行相应的命令(可以传递参数),可以通过输入流获取相应的结果,从而进行下一步操作。
模板代码如下:
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("python3.5 /home/liudong/PycharmProjects/bpann/webBPANN_interface.py");
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuilder =new StringBuilder();
while ((line = bufferedReader.readLine()) !=null){
System.out.println(line);
stringBuilder.append(line);
}
System.out.println(stringBuilder.toString());
System.out.println(process.waitFor());
}catch (Exception e) {
e.printStackTrace();
}