java如何运行Python文件程序

有时候会遇到在java中启动Python的程序,下面进行说明

package com.zxh.util;



import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * python执行器
 *
 * @Author zxh
 * @Date 2024/8/27 0027
 */
@Slf4j
public class PythonExecution {
    /**
     * 运行py文件
     *
     * @param directoryPath py文件的根路径
     * @param command       要执行的命令
     * @param params       参数
     */
    public static void execFile(String directoryPath, String command, LinkedHashMap<String,String> params) {
        try {
            //当前系统类型
            String os = System.getProperty("os.name");
            ProcessBuilder processBuilder = new ProcessBuilder();
            //分隔执行命令
            String[] s = command.split(" ");
            //切换到py文件的路径(指定路径去执行命令)
            processBuilder.directory(new File(directoryPath));
            ArrayList commandList = new ArrayList(Arrays.asList(s));
            //拼接需要的参数
            if(CollectionUtil.isNotEmpty(params)){
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    commandList.add(key);
                    commandList.add(params.get(key));
                }
            }
            processBuilder.command(commandList);
            Process process = processBuilder.start();
            //等待执行完成的后退出状态码,0表示成功,其他是失败
            int exitCode = process.waitFor();
            log.info("Command exited with code {}.执行结果:{}", exitCode, exitCode == 0);
            // 获取 Python 脚本的输出结果
            InputStream inputStream = process.getInputStream();
            //指定编码,py默认编码会导致乱码(windows系统)
            InputStreamReader inputStreamReader;
            String charsetName = "gb2312";
            if (os.startsWith("Windows")){
                inputStreamReader = new InputStreamReader(inputStream, charsetName);
            }else{
                inputStreamReader = new InputStreamReader(inputStream);
            }
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            Boolean isPrint = false;
            while ((line = reader.readLine()) != null) {
                if (!isPrint) {
                    log.info("py执行后返回结果:");
                }
                isPrint = true;
                log.info(line);
            }
            Boolean isError = false;
            // 获取 Python 脚本的错误信息
            InputStream errorStream = process.getErrorStream();
            InputStreamReader errorStreamReader;
            if (os.startsWith("Windows")){
                errorStreamReader = new InputStreamReader(errorStream, charsetName);
            }else{
                errorStreamReader = new InputStreamReader(errorStream);
            }
            BufferedReader errorReader = new BufferedReader(errorStreamReader);
            String errorLine;
            //按行读取错误信息
            while ((errorLine = errorReader.readLine()) != null) {
                if (!isError) {
                    log.info("py执行的错误信息:");
                }
                isError = true;
                log.info(errorLine);
            }
        } catch (IOException e) {
            log.error("执行py时出现异常:", e);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

test.py内容如下:

# encoding: utf-8
import sys
result = "Hello from Python!你好"
dataforJava2 = sys.argv[1:]
print(result)
print(dataforJava2)

直接调用,指定py文件的路径和文件名(原因:可能会存在当前运行的py文件和运行的java程序不在同一文件夹下)

    @GetMapping("/test")
    public void test(){
        //传递的参数
        LinkedHashMap<String,String> params = new LinkedHashMap<>();
        params.put("name","123");
        params.put("age","34");
        //linux系统使用的是python3的版本
        //PythonExecution.execFile("/usr/file","python3 test.py", params);
        //windows系统使用的是python2的版本
        PythonExecution.execFile("D:\\项目\\demo\\springboot-demo\\src\\main\\resources\\py","python test.py",params);
    }

执行结果

需要注意的是,对于windows系统py文件中返回值包含中文,则需要进行编码的设置,否则是乱码。

posted @ 2024-08-28 14:38  钟小嘿  阅读(131)  评论(0编辑  收藏  举报