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条经验 获得超3个赞
您过度使用了变量 。它不能既是当前的输出线,也不能是到目前为止看到的所有线。添加第二个变量以跟踪累积输出。line
String line;
StringBuilder output = new StringBuilder();
while ((line = in.readLine()) != null) {
output.append(line);
.append('\n');
}
System.out.println("value is : " + output);
添加回答
举报