java中调用python脚本
为maven项目导包
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.0</version>
</dependency>
简单的调用
新建.py文件
java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
Process proc;
try {
String[] cmdArr = new String[] {"python", "C:\\Users\\lei\\PycharmProjects\\numpy\\venv\\java.py"};
proc = Runtime.getRuntime().exec(cmdArr);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
执行main方法,获取到了python脚本中打印的内容。
调用python中的方法
随便写一个add方法。
java代码
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties props = new Properties();
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();
interpreter.execfile("C:\\Users\\lei\\PycharmProjects\\numpy\\venv\\java.py");
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyFunction pyFunction = interpreter.get("add", PyFunction.class);
int a = 2, b = 3;
//调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("方法调用成功,返回: " + pyobj);
}
}
执行mian方法,获取到返回内容