java如何调取python
调用 Python 的常见方法
在 Java 中调用 Python 脚本或功能可以通过多种方式实现,以下是几种常见的方法:
使用 ProcessBuilder 或 Runtime.exec
通过 Java 的 ProcessBuilder 或 Runtime.exec 启动 Python 进程,直接执行 Python 脚本。
ProcessBuilder processBuilder = new ProcessBuilder("python", "path/to/script.py", "arg1", "arg2");
Process process = processBuilder.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
Jython 是一个 Java 实现的 Python 解释器,可以直接在 Java 中调用 Python 代码。
import org.python.util.PythonInterpreter;
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python!')");
interpreter.execfile("path/to/script.py");
使用 Py4J
Py4J 是一个库,允许 Python 和 Java 通过本地套接字通信。

在 Python 端启动一个网关服务器:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
在 Java 端连接并调用 Python 方法:
import py4j.GatewayServer;
GatewayServer server = new GatewayServer(new YourJavaClass());
server.start();
使用 REST API
将 Python 功能封装为 RESTful 服务,Java 通过 HTTP 调用。

Python 端使用 Flask 框架:
from flask import Flask, request
app = Flask(__name__)
@app.route('/execute', methods=['POST'])
def execute():
data = request.json
return {"result": "Processed data"}
if __name__ == '__main__':
app.run(port=5000)
Java 端使用 HttpClient:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:5000/execute"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"data\":\"value\"}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
使用 Apache Commons Exec
Apache Commons Exec 提供了更高级的进程控制功能。
CommandLine cmdLine = new CommandLine("python");
cmdLine.addArgument("path/to/script.py");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
选择方法的考虑因素
- 简单脚本调用:
ProcessBuilder或Runtime.exec是最直接的方式。 - 紧密集成:Jython 或 Py4J 适合需要频繁交互的场景。
- 跨语言解耦:REST API 适合分布式或微服务架构。
- 进程管理:Apache Commons Exec 提供更完善的进程控制。
根据具体需求选择合适的方法,权衡性能、复杂度和维护成本。






