因此,我目前正在开发一个项目,该项目的GUI和Java脚本均使用Java来执行程序的主要功能。
我想知道是否有一种方法可以从应用程序目录中运行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);
}