【发布时间】:2011-10-22 13:24:52
【问题描述】:
在 python 中,如何检查来自 subprocess.Popen 对象的标准输出是否有任何要读取的内容?我正在围绕一个有时连续运行数小时的工具编写一个包装器。当运行超过几分钟时,在子进程的标准输出上使用 .readline() 会严重降低脚本的速度。如果有要阅读的内容,我需要一种更有效地检查标准输出的方法。顺便说一句,这个特殊的工具一次只写完整的行。脚本是这样的:
#!/usr/bin/python -u
#thiswrap.py
import sys, time
from subprocess import *
chldp = Popen(sys.argv[1], bufsize=0, stdout=PIPE, close_fds=True)
chstdin,chstdout=chldp.stdin,chldp.stdout
startnoti=False
while not chldp.poll():
rrl=chstdout.readline() # <--- this is where the problem is
if rrl[-8:]=='REDACTED TEXT':
sys.stdout.write(rrl[:-1]+' \r')
if not startnoti: startnoti=True
else:
if startnoti: sys.stdout.write('\n')
sys.stdout.write(rrl)
if startnoti: # REDACTED
time.sleep(0.1)
time.sleep(0.1)
有什么想法吗?
【问题讨论】:
-
为什么让
readline屏蔽会出问题?你为什么打电话给sleep? -
我将忽略有关 readline 阻塞的巨魔部分,并且 sleep 实际上只是一种权宜之计,直到我可以解决 readline 问题。我知道这有点懒惰和笨拙,但我不需要在代码的那部分中添加任何其他内容,除非它可能来自更好的解决方案来知道何时使用 readline() 所以它一直存在直到这个问题消失离开。
标签: python subprocess stdout popen readline