java 如何调用python
使用 ProcessBuilder 调用 Python 脚本
通过 Java 的 ProcessBuilder 类可以启动外部进程执行 Python 脚本。需要确保系统已安装 Python 并配置环境变量。
ProcessBuilder pb = new ProcessBuilder("python", "path/to/script.py", "arg1", "arg2");
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
使用 Jython 直接运行 Python 代码
Jython 是 Python 的 Java 实现,允许在 JVM 中直接执行 Python 代码。需添加 Jython 依赖(如 org.python:jython-standalone)。
import org.python.util.PythonInterpreter;
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python')");
interpreter.execfile("path/to/script.py");
通过 REST API 通信
若 Python 脚本已封装为 HTTP 服务,Java 可通过 HTTP 客户端(如 HttpURLConnection 或 OkHttp)调用接口。

URL url = new URL("http://localhost:5000/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = in.readLine();
in.close();
使用 Java Native Interface (JNI)
将 Python 代码编译为 C 库,再通过 JNI 调用。适用于高性能场景,但步骤复杂:
- 用 Cython 将 Python 代码转换为 C 库。
- 编写 JNI 桥接代码调用 C 库。
- 在 Java 中加载生成的动态链接库(
.dll或.so)。
通过消息队列(如 RabbitMQ)
Java 和 Python 通过消息队列异步通信。例如 Java 发送任务到队列,Python 消费并返回结果。

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("task_queue", false, false, false, null);
channel.basicPublish("", "task_queue", null, "data".getBytes());
使用 Py4J 库
Py4J 允许 Java 程序动态访问 Python 对象。需在 Python 端启动网关服务器:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
Java 端连接并调用方法:
import py4j.GatewayServer;
GatewayServer server = new GatewayServer(new JavaObject());
server.start();
注意事项
- 路径问题:确保 Python 脚本路径正确,或使用绝对路径。
- 依赖管理:Python 脚本所需的第三方库需预先安装。
- 错误处理:捕获
IOException和InterruptedException处理进程异常。 - 性能:频繁调用脚本时,考虑进程复用或改用 API/消息队列。
根据场景选择合适方法:简单脚本调用推荐 ProcessBuilder,复杂集成建议使用 REST 或消息队列。






