![](/img/trans.png)
[英]How to run parallel python scripts from java using the ProcessBuilder
[英]How to return value from Python script to Java using ProcessBuilder?
我試圖使用ProcessBuilder從python腳本獲取返回值到Java。 我期待Java中的值“這就是我要找的東西”。 任何人都可以指出我在下面的邏輯中有什么問題嗎?
我正在使用python3並希望使用java標准庫完成此操作。
test.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();
}
你過度使用變量line
。 它不能同時輸出的電流線和迄今所看到的所有行。 添加第二個變量以跟蹤累積的輸出。
String line;
StringBuilder output = new StringBuilder();
while ((line = in.readLine()) != null) {
output.append(line);
.append('\n');
}
System.out.println("value is : " + output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.