温馨提示×

java怎么调用python并获取返回值

小亿
142
2023-12-16 11:57:56
栏目: 编程语言

Java可以通过使用Runtime类来调用Python脚本并获取返回值。以下是一个示例代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PythonCaller {
    public static void main(String[] args) {
        try {
            // 创建Runtime对象
            Runtime runtime = Runtime.getRuntime();
            
            // 定义Python脚本路径和参数
            String pythonScriptPath = "path/to/your/python/script.py";
            String[] cmd = {"python", pythonScriptPath};
            
            // 执行Python脚本
            Process process = runtime.exec(cmd);
            
            // 获取脚本输出结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            
            // 等待脚本执行完成
            int exitCode = process.waitFor();
            
            // 打印脚本输出结果和执行状态
            System.out.println("脚本输出结果:\n" + output.toString());
            System.out.println("脚本执行状态码:" + exitCode);
            
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

请注意替换pythonScriptPath为你的Python脚本的路径。代码执行完毕后,将会输出Python脚本的返回值和执行状态码。

0