在子进程运行时拦截它的stdout [英] Intercepting stdout of a subprocess while it is running

查看:99
本文介绍了在子进程运行时拦截它的stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是我的子流程:

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

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

And this is the script controlling and modifying the output of the subprocess:

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?

Why is readline and communicate waiting until the process is done running? Is there a simple way to pass (and modify) the subprocess' stdout real-time?

顺便说一句,我已经看过,但我不需要日志记录功能(也不必担心太多).

BTW, I've seen this, but I don't need the logging features (and havn't bothered understand much of it).

我在Windows XP上.

I'm on Windows XP.

推荐答案

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

As Charles already mentioned, the problem is buffering. I ran in to a similar problem when writing some modules for SNMPd, and solved it by replacing stdout with an auto-flushing version.

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

I used the following code, inspired by some posts on 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__)

这篇关于在子进程运行时拦截它的stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆