在进程终止之前从java进程获取stdInput
因此,我试图运行一个python脚本,并希望从脚本中获取stdInput,以便使用它。我注意到stdInput将一直挂起,直到进程完成 Python脚本:在进程终止之前从java进程获取stdInput,java,python,process,runtime,blocking,Java,Python,Process,Runtime,Blocking,因此,我试图运行一个python脚本,并希望从脚本中获取stdInput,以便使用它。我注意到stdInput将一直挂起,直到进程完成 Python脚本: import time counter = 1 while True: print(f'{counter} hello') counter += 1 time.sleep(1) public class Main { public static void main(String[] args) throws
import time
counter = 1
while True:
print(f'{counter} hello')
counter += 1
time.sleep(1)
public class Main {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String[] commands = {"python3", "/Users/nathanevans/Desktop/Education/Computing/Programming/Java/getting script output/src/python/main.py"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
System.out.println("stdOuput of the command");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("stdError of the command");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
}
Java代码:
import time
counter = 1
while True:
print(f'{counter} hello')
counter += 1
time.sleep(1)
public class Main {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String[] commands = {"python3", "/Users/nathanevans/Desktop/Education/Computing/Programming/Java/getting script output/src/python/main.py"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
System.out.println("stdOuput of the command");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("stdError of the command");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
}
在进程终止之前,java应用程序不会打印任何内容,但在本例中,当我终止java应用程序时
如何获得脚本编写的stdInput?为了立即获得Python输出,您需要关闭Python输出缓冲,这已经介绍过了 这可能会解决您的问题,但您可能会遇到第二个问题,因为您正在一个线程中读取STD IN/OUT。如果在读取到STDIN结尾之前STDERR缓冲区已填充,则会阻止进程。然后,解决方案是在单独的线程中读取STD/IN/ERR,或者使用ProcessBuilder,它允许重定向到文件或将STDERR重定向到STDOUT:
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectOutput(outfile);
pb.redirectError(errfile);
//or
pb.redirectErrorStream(true);
Process p = pb.start();