为了账号安全,请及时绑定邮箱和手机立即绑定

逐行读取子过程标准输出

逐行读取子过程标准输出

弑天下 2019-06-19 15:59:33
逐行读取子过程标准输出我的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()
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

聚会有点晚了,但惊讶地没有看到我认为最简单的解决办法:

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


查看完整回答
反对 回复 2019-06-19
  • 3 回答
  • 0 关注
  • 474 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信