在运行时拦截子进程的stdout

Pau*_*aul 23 python subprocess stdout process popen

如果这是我的子流程:

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

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

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'
Run Code Online (Sandbox Code Playgroud)

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

顺便说一下,我已经看过,但是我不需要记录功能(并且没有太多的了解它).

我在Windows XP上.

Kam*_*iel 15

正如查尔斯已经提到的,问题在于缓冲.在为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__)
Run Code Online (Sandbox Code Playgroud)

  • 子进程中需要刷新,而不是父进程. (9认同)

Cha*_*ffy 8

过程输出被缓冲.在更多UNIXy操作系统(或Cygwin)上,可以使用pexpect模块,其中列出了所有必要的咒语以避免与缓冲相关的问题.但是,这些咒语需要一个工作的pty模块,这在本机(非cygwin)win32 Python构建中不可用.

在您控制子进程的示例情况下,您可以sys.stdout.flush()在必要时调用它- 但对于任意子进程,该选项不可用.

另见"为什么不使用管道(popen())?" 在pexpect FAQ中.