2 回答

TA貢獻1802條經驗 獲得超10個贊
當您從另一個進程生成一個進程時,它們只能(主要是)通過其輸入和輸出流進行通信。因此,你不能期望 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();
}

TA貢獻1872條經驗 獲得超4個贊
您過度使用了變量 。它不能既是當前的輸出線,也不能是到目前為止看到的所有線。添加第二個變量以跟蹤累積輸出。line
String line;
StringBuilder output = new StringBuilder();
while ((line = in.readLine()) != null) {
output.append(line);
.append('\n');
}
System.out.println("value is : " + output);
添加回答
舉報