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
仅在打印行以了解它们是否来自stderr
或时进行区分stdout
。