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



在我当前的程序中,我使用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所说的。您需要做的是让读循环将事件发送到主线程。不管是全局标志还是队列。查看一下queue的文档。

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'OKn'

最新更新