在Java中调用Python程序可以通过以下几种方法实现:
直接执行Python语句
使用`org.python.util.PythonInterpreter`类,可以直接在Java代码中执行Python语句。
import org.python.util.PythonInterpreter;
public class JavaRunPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'");
interpreter.exec("print(a)");
}
}
调用本地Python脚本中的函数
使用`ProcessBuilder`类执行Python解释器,并通过输入输出流与Python进程进行通信。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonCaller {
public static void main(String[] args) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_script.py");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
使用Java直接执行Python脚本
同样使用`ProcessBuilder`类,但这次是执行整个Python脚本。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonCaller {
public static void main(String[] args) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_script.py");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
使用Jython库
Jython是一个Python解释器,可以在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_your_script.py");
PyObject pyObject = interpreter.get("Test");
PyObject result = pyObject.__call__("hello");
System.out.println(result);
}
}
请确保Python解释器已正确安装,并且你的Python脚本路径是正确的。如果使用Maven,可以将Jython依赖添加到`pom.xml`文件中。
org.python jython-standalone
2.7.0
以上方法可以帮助你在Java程序中调用Python代码。选择适合你项目需求的方法进行实现