[英]Java program display the continuous output from Python
I would like to read the output from execute python script in time,but when I was doing this,java always waited the python until it finish(after 5 sec) all process. 我想及时读取执行python脚本的输出,但是当我这样做时,java总是等待python直到它完成(5秒后)所有进程。
I reproduced my question as following: 我的问题转载如下:
read.java read.java
public static void main(String[] args) throws IOException{
Runtime rt = Runtime.getRuntime();
String[] commands = {"python.exe","hello.py"}; //execute the hello.py under path
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
hello.py 你好
import time
print "123\n"
time.sleep(5) #wait 5 sec and print next line
print '456'
---update--- -更新-
I rewrote my code as following,but it seemed doesn't work. 我将代码重写如下,但是似乎不起作用。
public class Hello implements Runnable {
public void run() {
String[] commands = { "python.exe", "hello.py" };
ProcessBuilder pb = new ProcessBuilder(commands);
pb.inheritIO();
try {
Process p = pb.start();
int result = p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
(new Thread(new Hello())).start();
}
}
I would prefer ProcessBuilder
and inheritIO
, something like 我更喜欢
ProcessBuilder
和inheritIO
,像
String[] commands = { "python.exe", "hello.py" };
ProcessBuilder pb = new ProcessBuilder(commands);
pb.inheritIO();
try {
Process p = pb.start();
int result = p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
For your current solution to work, you would need to handle the IO in non-blocking threads. 为了使当前的解决方案有效,您需要在非阻塞线程中处理IO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.