subprocess.communicate仅在退出时读取

时间:2019-04-02 00:56:07

标签: python subprocess

我正在尝试在一个线程中运行一个子进程,该线程将定期输出数据(但每秒输出一次)

但是,当尝试读取进程的标准输出时,communicate(timeout=2)始终会遇到TimeoutError,即使应该有有效的标准输出数据也是如此。

该代码在带有daemon=True的线程的flask应用程序中运行。

我要运行的过程是

print("A")
time.sleep(1)
print("B")
time.sleep(5)
print("C")
exit()

哪个应该同时给我“ A”和“ B”而不会超时?

这是应该给我输出的循环:

with Popen(
        args=[get_python_path(), path.join(
            self.path, "output.py")],
        stdout=PIPE, stderr=PIPE, universal_newlines=True) as proc:
    self.status = RNNTrainer.STARTED
    status = None
    while status == None:
        try:
            stdout, stderr = proc.communicate(timeout=2)
            print(stdout)
            status = proc.returncode
        except TimeoutExpired as err:
            print("Timeout Expired")
            proc.poll()
            status == proc.returncode
        except Exception as err:
            print("Unhandled Ex")

我希望看到如下输出:

A
B
Timeout expired <-This after the sleep(5) call
C

但是,我却得到了

Timeout expired
Timeout expired
Timeout expired
A
B
C

换句话说。 .communicate仅在程序终止时有效。否则就结束了

1 个答案:

答案 0 :(得分:1)

flush=True添加到print()个呼叫

print("A", flush=True)
time.sleep(1)
print("B", flush=True)
time.sleep(5)
print("C", flush=True)
exit()

强制print()刷新流。

  

When interactive, stdout and stderr streams are line-buffered. Otherwise, they are block-buffered like regular text files. You can override this value with the -u command-line option.