[英]Intercepting stdout of a subprocess while it is running
If this is my subprocess: 如果这是我的子流程:
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'
Why is readline
and communicate
waiting until the process is done running? 为什么readline
和communicate
等到过程完成后再运行? Is there a simple way to pass (and modify) the subprocess' stdout real-time? 有没有简单的方法可以实时传递(和修改)子进程的stdout?
BTW, I've seen this , but I don't need the logging features (and havn't bothered understand much of it). 顺便说一句,我已经看过了 ,但是我不需要日志记录功能(也不必费心了解很多功能)。
I'm on Windows XP. 我在Windows XP上。
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. 在为SNMPd编写一些模块时遇到了类似的问题,并通过用自动刷新版本替换stdout来解决了该问题。
I used the following code, inspired by some posts on ActiveState: 我使用了以下代码,这些代码受到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__)
Process output is buffered. 进程输出被缓冲。 On more UNIXy operating systems (or Cygwin), the pexpect module is available, which recites all the necessary incantations to avoid buffering-related issues. 在更多的UNIXy操作系统(或Cygwin)上,可以使用pexpect模块,该模块列举了所有必要的方法以避免与缓冲相关的问题。 However, these incantations require a working pty module , which is not available on native (non-cygwin) win32 Python builds. 但是,这些要求需要一个有效的pty模块 ,该模块在本机(非Cygwin)win32 Python构建中不可用。
In the example case where you control the subprocess, you can just have it call sys.stdout.flush()
where necessary -- but for arbitrary subprocesses, that option isn't available. 在控制子流程的示例中,只要需要,就可以调用sys.stdout.flush()
,但是对于任意子流程,该选项不可用。
See also the question "Why not just use a pipe (popen())?" 另请参见问题“为什么不只使用管道(popen())?” in the pexpect FAQ. 在pexpect常见问题解答中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.