使用Java运行Python应用程序,然后解析其输出

使用Java运行Python应用程序,然后解析其输出,java,python,Java,Python,因此,我目前正在从事一个项目,该项目使用Java作为GUI,并使用python脚本来执行程序的主要功能 我想知道是否有办法从应用程序目录中运行python脚本,然后将其输出发送到GUI程序进行解析。输出可以是JSON/YAML/Plaintext等,因此GUI将对其进行解析 我想到的两个可能有效也可能无效的选择是: 单独运行Python程序并让它输出一个文件,然后由Java程序读取,这是我最不喜欢的 使用ProcessBuilder或Runtime.exec运行Python程序。。但是我怎样才能

因此,我目前正在从事一个项目,该项目使用Java作为GUI,并使用python脚本来执行程序的主要功能

我想知道是否有办法从应用程序目录中运行python脚本,然后将其输出发送到GUI程序进行解析。输出可以是JSON/YAML/Plaintext等,因此GUI将对其进行解析

我想到的两个可能有效也可能无效的选择是:

单独运行Python程序并让它输出一个文件,然后由Java程序读取,这是我最不喜欢的 使用ProcessBuilder或Runtime.exec运行Python程序。。但是我怎样才能得到输出呢? 如果我想到的两种选择都不可行或行不通,那么有没有更好的方法


谢谢

Runtime.exec为您提供一个输入流,可以将其包装在缓冲读取器中以解析输出

      try {

        Process p = Runtime.getRuntime().exec("python 1.py'");

        BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

        System.exit(0);
    }
    catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }

你的例子很不清楚。对我来说,它看起来就像是你在一个名为write.txt的文件中阅读,因此它并没有真正回答我的问题,即我是否可以有效地执行python脚本以获得其输出。这两种方法都可以工作,但我更喜欢ProcessBuilderredirectOutputRedirect和redirectError。使用单独的线程读取流,否则进程在填充其输出缓冲区后可能会挂起。