2024.1.15-每日进度笔记

佚名 / 2024-01-15 / 原文

今天,我尝试在java中对昨天的python脚本进行调用,并尝试对输出结果进行格式化。

 

参考:百度文心一言的回复。

 

package test0113;

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

public class test0115 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        String res = getScore("D:\\test0114.png", "题目123456", "5");
        System.out.println("返回结果:" + res);
    }

    public static String getScore(String input_path, String question, String total_score) {
        String res = "";
        String pythonPath = "D:\\softdata\\Anaconda_envs\\envs\\paddle_env\\python.exe"; // 指定Python解释器路径
        String scriptPath = "D:\\develop\\PycharmProjects\\paddle\\test4.py"; // 指定Python脚本路径
        String[] scriptArgs = { input_path, question, total_score }; // 指定Python脚本参数

        ProcessBuilder pb = new ProcessBuilder(pythonPath, scriptPath);
        // pb.redirectErrorStream(true); // 将标准输出和标准错误合并为同一流

        pb.command().addAll(Arrays.asList(scriptArgs));
        try {
            Process p = pb.start(); // 启动进程

            // 获取进程的标准输出流和标准错误流
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // 打印进程的标准输出流信息
            String line;
            while ((line = stdInput.readLine()) != null) {
                System.out.println("Standard Output of the Python script: " + line);
                line = line.replaceAll(" ", "");
                if (line.contains("分数")) {
                    res = res + line.split("分数(:|:)|分", 3)[1] + "-";
                }
                if (line.contains("评语")) {
                    res = res + line.split("评语(:|:)", 2)[1];
                }
            }
            stdInput.close();

            // 打印进程的标准错误流信息
            while ((line = stdError.readLine()) != null) {
                System.out.println("Standard Error of the Python script: " + line);
            }
            stdError.close();

            int exitCode = p.waitFor(); // 等待进程结束并获取退出码
            System.out.println("Python脚本执行完毕,退出码为:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return res;
    }
}