java如何调用 py
调用 Python 脚本的方法
Java 可以通过多种方式调用 Python 脚本,以下是几种常见的方法:
使用 Runtime 类执行 Python 脚本
通过 Java 的 Runtime 类可以调用系统命令执行 Python 脚本:

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunPython {
public static void main(String[] args) {
try {
String pythonScriptPath = "path/to/your/script.py";
String[] cmd = new String[3];
cmd[0] = "python";
cmd[1] = pythonScriptPath;
cmd[2] = "argument1"; // 可选参数
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 ProcessBuilder 类
ProcessBuilder 提供了更灵活的方式来构建进程:
ProcessBuilder pb = new ProcessBuilder("python", "script.py", "arg1", "arg2");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
使用 Jython
Jython 是 Python 的 Java 实现,可以直接在 Java 中调用 Python 代码:

import org.python.util.PythonInterpreter;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python!')");
}
}
使用 REST API
如果 Python 脚本提供了 REST API,可以通过 HTTP 请求调用:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RestClient {
public static void main(String[] args) {
try {
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 line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Py4J
Py4J 允许 Python 程序访问 Java 对象,也可以从 Java 调用 Python:
import py4j.GatewayServer;
public class Py4JExample {
public static void main(String[] args) {
GatewayServer server = new GatewayServer(new Py4JExample());
server.start();
System.out.println("Gateway Server Started");
}
}
注意事项
- 确保系统已安装 Python 并配置了环境变量
- 处理 Python 脚本的输出流和错误流
- 考虑跨平台兼容性
- 对于复杂交互,建议使用 REST API 或消息队列
- 性能敏感场景考虑 JNI 或其他高性能方案
以上方法各有优缺点,选择哪种方式取决于具体需求、性能要求和系统环境。






