subprocess.communicate仅在退出时读取

问题描述 投票:1回答:1

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

但是,当尝试读取进程的标准输出时,communicate(timeout=2)总是会遇到TimeoutError,即使有效的stdout数据应该可用。

代码在一个使用daemon=True生成的线程中的烧瓶应用程序中运行。

我试图运行的过程是

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仅在程序终止时有效。否则它就结束了

python subprocess
1个回答
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.

© www.soinside.com 2019 - 2024. All rights reserved.