import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CallPythonFromJava { public static void main(String[] args) { try { // 创建Python进程 ProcessBuilder processBuilder = new ProcessBuilder("python", "my_module.py"); processBuilder.redirectErrorStream(true); // 合并错误流到输出流 Process process = processBuilder.start(); // 获取Python输出流 InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); // 实时输出 String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待进程结束 int exitCode = process.waitFor(); System.out.println("Python process exited with code " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
参考资料:https://blog.csdn.net/2301_79533350/article/details/132973965