Java项目调用Python脚本(基于idea)

前期准备

1.首先需要在本地环境中安装配置python环境

Python(含PyCharm及配置)下载安装以及简单使用(Idea)

博主本次使用python版本为py3.7.3

2.idea安装python插件

位置:File->Settings->Plugins->python->安装后重启即可
在这里插入图片描述

3.引入jython依赖

<!--python-->
<dependency>
   <groupId>org.python</groupId>
   <artifactId>jython-standalone</artifactId>
   <version>2.7.0</version>
</dependency>

编写Java代码

1.方式1:

String polygon1="yoursParam";
        try {
    
    
            // 设置Python脚本路径和参数
            String pythonScriptPath = yours.py";
            // 构建命令
            String command = "python " + pythonScriptPath + " " + polygon1;

            try {
    
    
                // 执行命令
                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);
                }

                // 等待脚本执行完毕
                process.waitFor();

                reader.close();
            } catch (IOException | InterruptedException e) {
    
    
                e.printStackTrace();
            }

2.方式2:

try {
    
    
            // 创建命令列表
            List<String> command = new ArrayList<>();
            command.add("python");
            command.add(yoursUrl);
            command.add(yoursParam);
            // 创建进程生成器并执行命令
            ProcessBuilder pb = new ProcessBuilder(command);
            Process process = pb.start();
            // 读取脚本输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String output;
            while ((output = reader.readLine()) != null) {
    
    
                System.out.println(output );
            }
            // 等待脚本执行完毕
            process.waitFor();
        } catch (IOException | InterruptedException e) {
    
    
            e.printStackTrace();
        }

两种方式区别

参数的形式:
1.Runtime.getRuntime().exec(command) 接受一个字符串形式的命令,例如 “python your_script.py”.
2.ProcessBuilder 接受一个命令的字符串列表,例如 {“python”, “your_script.py”}. 使用列表形式可以更灵活地传递参数和配置。

管理进程的能力:
1.Runtime.getRuntime().exec(command) 返回一个 Process 对象,但对于该进程的控制和管理能力有限。
2.ProcessBuilder 返回一个 ProcessBuilder 对象,该对象可以进行更高级的进程控制,例如重定向输入输出流、设置环境变量、设置工作目录等。

子进程输出的处理:
1.Runtime.getRuntime().exec(command) 需要手动处理子进程的输入流和输出流,否则可能会导致进程阻塞或数据丢失。
2.ProcessBuilder 在调用 start() 方法后,可以通过 Process 对象的 getInputStream()、getOutputStream() 和 getErrorStream() 方法来获取子进程的标准输入、输出和错误输出流。

python脚本此处不再展示 可根据自己情况传值调用即可 可通过文件方式传值 py处用pandas库中方法读取xlsx或者txt等都可自行选择 如若直接传值可用Processbuilder 命令行获取参数即可 py对应方法为sys.argv 基于sys库

猜你喜欢

转载自blog.csdn.net/weixin_45735355/article/details/133782751