[英]Real-time intercepting of stdout from another process in Python
我想运行一个系统进程,拦截输出,并在 Python 脚本中逐行实时修改它。
我最好的尝试,在打印之前等待过程完成,是:
#!/usr/bin/env python
import subprocess
cmd = "waitsome.py"
proc = subprocess.Popen(cmd, shell=True, bufsize=256, stdout=subprocess.PIPE)
for line in proc.stdout:
print ">>> " + line.rstrip()
脚本waitsome.py
只是每半秒打印一行:
#!/usr/bin/env python
import time
from sys import stdout
print "Starting"
for i in range(0,20):
time.sleep(0.5)
print "Hello, iteration", i
stdout.flush()
是否有一个简单的解决方案来获取subprocess
以允许实时迭代输出? 我必须使用线程吗?
曾几何时,我用 Perl 编写脚本,这是小菜一碟:
open(CMD, "waitsome.py |");
while (<CMD>) {
print ">>> $_";
}
close(CMD);
循环遍历文件不可避免地会以相当大的块缓冲内容——这是所有 Python 2.* 实现的一个已知问题。 它在 Python 3.1 中按您的预期工作,最终循环略有不同:
for line in proc.stdout:
print(">>> " + str(line.rstrip()))
如果升级到 Python 3.1 是不切实际的(我知道它经常是!),请换一种方式并以老式的方式编写循环 - 以下版本的循环确实可以在 Python 2.* 中正常工作。 :
while True:
line = proc.stdout.readline()
if not line:
break
print ">>> " + line.rstrip()
这整个事情可以封装在一个迭代器中:
def subprocess_readlines(out):
while True:
line = out.readline()
if not line:
return
yield line
并称为:
for line in subprocess_readlines(proc.stdout):
print ">>>", line.rstrip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.