Java可以通过Runtime类或ProcessBuilder类调用外部进程执行命令,因此可以通过这种方式调用Python脚本。下面是一个示例代码:

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

public class PythonCaller {
    public static void main(String[] args) {
        try {
            String[] command = {"python", "path_to_script.py", "arg1", "arg2"};
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这个示例代码中,调用了Python脚本path_to_script.py,并传入了两个参数arg1arg2,然后通过BufferedReader读取Python脚本的输出,并在控制台上打印出来。如果Python脚本执行过程中发生异常,则会在控制台上打印出堆栈信息

用Java实现调用python脚本

原文地址: https://www.cveoy.top/t/topic/drrt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录