在Java中调用Python脚本可以通过以下几种方法:
使用Runtime类的exec方法
try {
String command = "python path/to/python/script.py";
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
使用ProcessBuilder类
ProcessBuilder pb = new ProcessBuilder("python", "path/to/python/script.py");
Process process = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
使用Jython库
首先,需要下载Jython的jar文件,并将其添加到Java项目的类路径中。然后可以使用`PythonInterpreter`类来执行Python脚本:
import org.python.util.PythonInterpreter;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("path/to/python/script.py");
}
}
使用org.python包
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class PythonInJava {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("path/to/python/script.py");
PyObject result = interpreter.get("result");
System.out.println(result);
}
}
请根据您的具体需求选择合适的方法。如果Python脚本需要与Java代码交互,可能需要使用`ProcessBuilder`类,因为它允许传递命令行参数和读取标准输出。如果只是简单地执行Python脚本,`Runtime`类的`exec`方法就足够了。