Intercepting stdout of a subprocess while it is running(在运行时拦截子进程的标准输出)
问题描述
如果这是我的子流程:
import time, sys
for i in range(200):
sys.stdout.write( 'reading %i
'%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'
为什么 readline
和 communicate
一直等到进程完成运行?有没有一种简单的方法可以实时传递(和修改)子进程的标准输出?
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?
我使用的是 Windows XP.
I'm on Windows XP.
推荐答案
正如 Charles 已经提到的,问题在于缓冲.我在为 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__)
这篇关于在运行时拦截子进程的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在运行时拦截子进程的标准输出


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01