防止stdout.readline()冻结程序的方法

Way to prevent stdout.readline() from freezing program

在我当前的程序中,我使用 subprocess.Popen() 启动服务器并使用 readline() 继续从 stdout 读取。但是,当它卡在 readline 上直到出现新行时。这很糟糕,因为我需要能够在等待服务器输出的同时执行其他代码。有什么办法可以阻止这种情况发生吗?

import subprocess

server = subprocess.Popen("startup command", stdout= subprocess.PIPE, encoding= "utf-8")

while True:
    out = server.stdout.readline()
    if out != "":
        print(out)
    print("checked for line")

我宁愿避免使用多线程,因为我的代码的不同部分将不再是线程安全的。

您将要像@tim Roberts 所说的那样使用线程。您需要做的是将读取循环 post 事件发送到主线程。无论是全局标志还是队列。查看队列的文档。

https://docs.python.org/3/library/queue.html

改用poll()communicate()

import subprocess
import time

with subprocess.Popen(['bash', '-c', 'sleep 1 && echo OK'], stdout=subprocess.PIPE) as proc:
    while proc.poll() is None:
        print('<doing something useful>')
        time.sleep(0.3)
    out, err = proc.communicate()
    print(out)
<doing something useful>
<doing something useful>
<doing something useful>
<doing something useful>
b'OK\n'