java如何调用py
调用 Python 脚本的几种方法
通过 Runtime 执行 Python 脚本
使用 Java 的 Runtime 类可以执行系统命令,直接调用 Python 解释器运行脚本。
Process process = Runtime.getRuntime().exec("python /path/to/script.py arg1 arg2");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
使用 ProcessBuilder
ProcessBuilder 提供了更灵活的方式来构建子进程,可以设置环境变量和工作目录。
ProcessBuilder pb = new ProcessBuilder("python", "/path/to/script.py", "arg1", "arg2");
pb.directory(new File("/working/directory"));
Process process = pb.start();
// 处理输出和错误流同上
通过 Jython 直接调用 Python 代码
Jython 是一个 Java 实现的 Python 解释器,可以直接在 Java 中运行 Python 代码。
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python')");
interpreter.execfile("/path/to/script.py");
使用 Apache Commons Exec
Apache Commons Exec 库提供了更高级的进程控制功能。
CommandLine cmdLine = new CommandLine("python");
cmdLine.addArgument("/path/to/script.py");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
通过 REST API 调用
将 Python 代码部署为 Web 服务,Java 通过 HTTP 请求调用。
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:5000/api"))
.POST(HttpRequest.BodyPublishers.ofString("input_data"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
使用 Py4J
Py4J 允许 Java 程序动态访问 Python 对象。

GatewayServer server = new GatewayServer(new MyJavaClass());
server.start();
// Python 端通过 Py4J 连接并调用 Java 方法
注意事项
- 确保系统环境变量中包含 Python 解释器路径
- 处理子进程的输入/输出流时要注意缓冲区问题
- 跨平台路径处理建议使用
File.separator - 考虑性能开销,频繁调用脚本建议使用 Jython 或 Web 服务方式
- 错误处理需要捕获
IOException和InterruptedException






