gpt4 book ai didi

Java程序显示Python的连续输出

转载 作者:行者123 更新时间:2023-12-01 20:16:45 25 4
gpt4 key购买 nike

我想及时读取执行Python脚本的输出,但是当我这样做时,java总是等待Python直到它完成(5秒后)所有过程。

我将我的问题重现如下:

读取.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);
}

你好.py

import time

print "123\n"
time.sleep(5) #wait 5 sec and print next line
print '456'

---更新---

我重写了我的代码如下,但它似乎不起作用。

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();
}

}

最佳答案

我更喜欢ProcessBuilderinheritIO ,类似

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();
}

要使当前的解决方案发挥作用,您需要在非阻塞线程中处理 IO。

关于Java程序显示Python的连续输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45667561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com