我正在尝试使用 ProcessBuilder 将 python 脚本的返回值返回到 Java 中。我期待 Java 中的值“这就是我正在寻找的”。谁能指出以下逻辑有什么问题?
我正在使用 python3 并希望使用 java 标准库完成此操作。
测试.py代码
import sys
def main33():
return "This is what I am looking for"
if __name__ == '__main__':
globals()[sys.argv[1]]()
Java代码
String filePath = "D:\\test\\test.py";
ProcessBuilder pb = new ProcessBuilder().inheritIO().command("python", "-u", filePath, "main33");
Process p = pb.start();
int exitCode = p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
line = in.readLine();
while ((line = in.readLine()) != null){
line = line + line;
}
System.out.println("Process exit value:"+exitCode);
System.out.println("value is : "+line);
in.close();
输出
Process exit value:0
value is : null
最佳答案
当您从另一个进程生成一个进程时,它们只能(主要是)通过它们的输入和输出流进行通信。因此你不能期望 python 中 main33() 的返回值到达 Java,它只会在 Python 运行时环境中结束它的生命。如果您需要将某些内容发送回 Java 进程,您需要将其写入 print()。
修改了你的 python 和 java 代码片段。
import sys
def main33():
print("This is what I am looking for")
if __name__ == '__main__':
globals()[sys.argv[1]]()
#should be 0 for successful exit
#however just to demostrate that this value will reach Java in exit code
sys.exit(220)
public static void main(String[] args) throws Exception {
String filePath = "D:\\test\\test.py";
ProcessBuilder pb = new ProcessBuilder()
.command("python", "-u", filePath, "main33");
Process p = pb.start();
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
StringBuilder buffer = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null){
buffer.append(line);
}
int exitCode = p.waitFor();
System.out.println("Value is: "+buffer.toString());
System.out.println("Process exit value:"+exitCode);
in.close();
}
关于java - 如何使用 ProcessBuilder 将值从 Python 脚本返回到 Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388121/