猿问

逐行读取子过程标准输出

逐行读取子过程标准输出

我的python脚本使用子进程来调用一个非常嘈杂的Linux实用程序。我想将所有的输出存储到一个日志文件中,并将其中的一些显示给用户。我认为下面的输出可以工作,但是直到实用程序产生了大量的输出之后,输出才会出现在我的应用程序中。

#fake_utility.py, just generates lots of output over timeimport time
i = 0while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)#filters outputimport 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()如果将代码添加到false_utility.py中,则该代码在python3.1中具有所需的行为。我正在使用python2.6。你会觉得用proc.stdout.xreadlines()会和py3k一样工作,但它不起作用。


更新2:

这是最低限度的工作代码。

#fake_utility.py, just generates lots of output over timeimport sys, timefor i in range(10):
   print i
   sys.stdout.flush()
   time.sleep(0.5)#display out put line by lineimport 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()


弑天下
浏览 475回答 3
3回答

烙印99

聚会有点晚了,但惊讶地没有看到我认为最简单的解决办法:import ioimport subprocess proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):   # or another encoding     # do something with line
随时随地看视频慕课网APP

相关分类

Python
我要回答