繁体   English   中英

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

[英]Intercepting stdout of a subprocess while it is running

如果这是我的子流程:

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上。

正如查尔斯已经提到的那样,问题正在缓冲。 在为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__)

进程输出被缓冲。 在更多的UNIXy操作系统(或Cygwin)上,可以使用pexpect模块,该模块列举了所有必要的方法以避免与缓冲相关的问题。 但是,这些要求需要一个有效的pty模块 ,该模块在本机(非Cygwin)win32 Python构建中不可用。

在控制子流程的示例中,只要需要,就可以调用sys.stdout.flush() ,但是对于任意子流程,该选项不可用。

另请参见问题“为什么不只使用管道(popen())?” 在pexpect常见问题解答中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM