在Java中调用Python脚本可以使用以下几种方法:
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();
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库,然后可以直接在Java代码中调用Python代码:
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("path/to/python/script.py");
PyObject someFunc = interpreter.get("someFunc");
someFunc.__call__();
}
}
这些是在Java中调用Python脚本的几种常用方法,可以根据具体需求选择适合的方法。