如何获取subprocess.call的stdout和stderr?

问题描述:

我使用的是subprocess.call,我需要获取stdout和stderr的输出。我怎样才能做到这一点?如何获取subprocess.call的stdout和stderr?

通知check_output()

注意不要使用标准输出=管或标准错误= PIPE使用此功能。 由于在当前进程中没有读取管道,如果子进程生成足够的输出到管道来填充OS管道缓冲区,则可能会阻止 。

我的调用可能会产生很多输出,那么获取输出的安全方法是什么?

+0

'check_output'会怎么做你想要什么,除非你需要分开吧。它告诉你不要使用'subprocess.PIPE'作为'stdout'和'stderr'的参数。 – 2013-10-25 16:24:25

像这样的工作:

f = file('output.txt','w') 
g = file('err.txt','w') 

p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=g) 

f.close() 
g.close() 

创建一个打开的文件对象,并将其作为sdtoutstderr传递。