【问题标题】:Process (python script -> py2exe ) InputStream is NULL until Process ends进程(python 脚本 -> py2exe ) InputStream 为 NULL 直到进程结束
【发布时间】:2014-03-12 17:46:53
【问题描述】:

我正试图赶上Process 的输出,如下所示:

new Thread() {
    public void run() {

        final ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "myexec.exe");

        p = builder.start();

        InputStream i = p.getInputStream();
        Reader r = new InputStreamReader(i, "US-ASCII");

        int ch = 32;

        do {
           System.out.print(ch);
        } while ((ch = r.read()) != -1);

    }
}.start();

正如我所见,当Process 正在运行ch == null 时,当Process 终止时,所有丢失的字符都会突然打印出来。

Process 运行期间如何读取输出?

【问题讨论】:

  • 你需要一个线程来读取输出。
  • 为什么?同样的情况是当我使用另一个线程来捕获输出时:p = builder.start(); StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream()); outputGobbler.start();
  • 是的。其中,outputGobbler 是一个线程。

标签: java python multithreading process py2exe


【解决方案1】:

您需要生成额外的线程来使用流中的数据并在主线程中等待进程完成:

...
p = builder.start();

new Thread() {
    public void run() {
        InputStream i = p.getInputStream();
        Reader r = new InputStreamReader(i, "US-ASCII");

        int ch = 32;

        do {
            System.out.print(ch);
        } while ((ch = r.read()) != -1);
    }
}.start();

// wait for process to complete while thread above consumes data
p.waitFor();

【讨论】:

  • 不幸的是它没有区别..仍然只有在进程完成后才能看到进程输出
  • 那么进程可能会在完成之前产生输出。
【解决方案2】:

好的,我得到了解决方案。 myexec.exe 是由 py2exe 生成的可执行 python 文件。

由于How to flush output of Python print? 我在每个print 函数之后加上sys.stdout.flush(),问题就消失了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2014-12-17
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多