![](/img/trans.png)
[英]Continuously process large amounts of stdout and stderr from a child process
[英]Processing messages from a child process thorough stderr and stdout with Python
我的python代码生成子进程,它打印出stdout和stderr的消息。 我需要以不同的方式打印它们。
我有以下代码来生成子进程并从中获取stdout结果。
cmd = ["vsmake.exe", "-f"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
print line,
sys.stdout.flush()
pass
p.wait()
如何修改代码以检查子进程是否也通过stderr打印出消息?
一旦子进程打印出来,我需要打印出stderr和stdout。 它是跨平台实现,因此它应该在Mac / Linux / PC上运行。
p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.close()
print p.stdout.read() #This will print the standard output from the spawned process
print p.stderr.read() #This is what you need, error output <-----
所以基本上错误输出被重定向到stderr
管道。
如果你需要更实际的东西及时。 我的意思是,一旦产生的进程将某些内容打印到stdout or
stderr`,就会打印出行,然后您可以执行以下操作:
def print_pipe(type_pipe,pipe):
for line in iter(pipe.readline, ''):
print "[%s] %s"%(type_pipe,line),
p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
t1 = Thread(target=print_pipe, args=("stdout",p.stdout,))
t1.start()
t2 = Thread(target=print_pipe, args=("stderr",p.stderr,))
t2.start()
#optionally you can join the threads to wait till p is done. This is avoidable but it
# really depends on the application.
t1.join()
t2.join()
在这种情况下,每次将一行写入stdout
或stderr
时,将打印两个线程。 参数type_pipe
只是在打印type_pipe
进行区分,以确定它们是来自stderr
还是stdout
。
独立完成此平台的最简单方法是使用线程(不幸的是)。 这是一些示例代码:
def redirect_to_stdout(stream):
for line in stream:
sys.stdout.write(line)
sys.stdout.flush()
cmd = ["vsmake.exe", "-f"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr_thread = threading.Thread(target=redirect_to_stdout, args=(p.stderr,))
stderr_thread.start()
redirect_to_stdout(p.stdout)
p.wait()
stderr_thread.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.