簡體   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