pro*_*eek 6 python stdout stderr spawn child-process
我的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()
Run Code Online (Sandbox Code Playgroud)
如何修改代码以检查子进程是否也通过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 <-----
Run Code Online (Sandbox Code Playgroud)
所以基本上错误输出被重定向到stderr管道.
如果你需要更实际的东西及时.我的意思是,一旦产生的过程打印到stdout orstderr`那么就会打印出行,然后你可以做类似的事情:
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()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,每次将一行写入stdout或将打印两个线程stderr.该参数type_pipe只是在打印线条时进行区分,以确定它们是来自stderr还是来自stdout.
| 归档时间: |
|
| 查看次数: |
1784 次 |
| 最近记录: |