java如何运行Python文件程序

笨兮兮 / 2024-08-28 / 原文

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

package com.zxh.util;

import lombok.extern.slf4j.Slf4j;

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

/**
 * python执行器
 *
 * @Author zxh
 * @Date 2024/8/27 0027
 */
@Slf4j
public class PythonExecution {
    /**
     * 运行py文件
     *
     * @param directoryPath py文件的根路径
     * @param command       要执行的命令
     */
    public static void execFile(String directoryPath, String command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            //切换到py文件的路径并执行命令
            processBuilder.command("cmd.exe", "/c", "cd /d " + directoryPath + " && " + command);
            Process process = processBuilder.start();
            //等待执行完成的后退出状态码,0表示成功,其他是失败
            int exitCode = process.waitFor();
            log.info("Command exited with code {}.执行结果:{}", exitCode, exitCode == 0);
            // 获取 Python 脚本的输出结果
            InputStream inputStream = process.getInputStream();
            //指定编码,py默认编码会导致乱码
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
            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();
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
            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内容如下:

result = "Hello from Python!你好"
print(result)

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

    public static void main(String[] args)  {
        String directoryPath = "D:\\项目\\demo\\springboot-demo\\src\\main\\resources\\py";
        String command = "python test.py";
        PythonExecution.execFile(directoryPath, command);
    }

执行结果

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