【发布时间】:2018-06-19 09:15:33
【问题描述】:
我的 python 脚本使用 subprocess 来调用一个非常嘈杂的 linux 实用程序。我想将所有输出存储到一个日志文件中,并将其中的一些显示给用户。我认为以下方法可行,但在实用程序产生大量输出之前,输出不会显示在我的应用程序中。
#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
print hex(i)*512
i += 1
time.sleep(0.5)
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
#the real code does filtering here
print "test:", line.rstrip()
我真正想要的行为是让过滤器脚本打印从子进程接收到的每一行。有点像 tee 所做的,但使用的是 python 代码。
我错过了什么?这甚至可能吗?
更新:
如果将sys.stdout.flush() 添加到 fake_utility.py,则代码在 python 3.1 中具有所需的行为。我正在使用python 2.6。你会认为使用proc.stdout.xreadlines() 会和py3k 一样工作,但事实并非如此。
更新 2:
这是最小的工作代码。
#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
print i
sys.stdout.flush()
time.sleep(0.5)
#display out put line by line
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
#works in python 3.0+
#for line in proc.stdout:
for line in iter(proc.stdout.readline,''):
print line.rstrip()
【问题讨论】:
-
您可以使用
print line,代替print line.rstrip()(注意:末尾的逗号)。 -
更新 2 声明它适用于 python 3.0+,但使用旧的 print 语句,因此它不适用于 python 3.0+。
-
这里列出的答案都没有对我有用,但 *.com/questions/5411780/… 对我有用!
-
有趣的代码只适用于 python3.0+ 使用 2.7 语法进行打印。
标签: python subprocess