gpt4 book ai didi

Java:有没有办法运行系统命令并在执行期间打印输出?

转载 作者:太空狗 更新时间:2023-10-30 02:32:18 25 4
gpt4 key购买 nike

我有一个 python 脚本,需要很长时间才能完成。我想从 Java 运行它,但也在它执行时输出脚本的输出,这样我就可以判断它是否正常运行。

我搜索过,只找到了在系统命令完成后而不是在执行期间输出输出的示例。

有什么方法可以在脚本运行时执行此操作?

这是我的

public void doSomething() throws IOException {
String[] callAndArgs = {"python", "/hi.py"};
Process p = Runtime.getRuntime().exec(callAndArgs);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

String s;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}

最佳答案

我设法让它像这样工作(注意它需要 java7):

package test;
import java.lang.ProcessBuilder.Redirect;

public class Test {

public static void main(String... args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("python","/home/foobar/Programming/test/src/test/test.py");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
p.waitFor();
}

}

python(注意我在 python 上刷新以使用 sys.stdout.flush() 使其工作)

import time,sys
c =0
while c<=50:
time.sleep(1)
print("----")
c = c +1
sys.stdout.flush()

注意如果你不想在循环中刷新你可以使用这个:

ProcessBuilder pb = new ProcessBuilder("python","-u","/home/foobar/Programming/NetBeansProjects/test/src/test/test.py");

重定向继承

Indicates that subprocess I/O source or destination will be the same as those of the current process. This is the normal behavior of most operating system command interpreters (shells).

关于Java:有没有办法运行系统命令并在执行期间打印输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102989/

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