小编典典

在子进程运行时拦截它的stdout

python

如果这是我的子流程:

import time, sys
for i in range(200):
    sys.stdout.write( 'reading %i\n'%i )
    time.sleep(.02)

这是控制和修改子流程输出的脚本:

import subprocess, time, sys

print 'starting'

proc = subprocess.Popen(
    'c:/test_apps/testcr.py',
    shell=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE  )

print 'process created'

while True:
    #next_line = proc.communicate()[0]
    next_line = proc.stdout.readline()
    if next_line == '' and proc.poll() != None:
        break
    sys.stdout.write(next_line)
    sys.stdout.flush()

print 'done'

为什么readlinecommunicate等待,直到程序完成后运行?有没有简单的方法可以实时传递(和修改)子进程的stdout?

顺便说一句,我已经看过,但是我不需要日志记录功能(也不必费心了解很多功能)。

我在Windows XP上。


阅读 154

收藏
2021-01-20

共1个答案

小编典典

正如查尔斯已经提到的那样,问题正在缓冲。在为SNMPd编写一些模块时遇到了类似的问题,并通过用自动刷新版本替换stdout来解决了该问题。

我使用了以下代码,这些代码受ActiveState上的一些帖子启发:

class FlushFile(object):
    """Write-only flushing wrapper for file-type objects."""
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

# Replace stdout with an automatically flushing version
sys.stdout = FlushFile(sys.__stdout__)
2021-01-20