python subprocess获取stdout和stderr

本文转载自http://www.firefoxbug.com/index.php/archives/2419/,如有版权问题请联系博主删除

用subprocess的时候,怎么获取stdout和stderr?下面是一种方式

import subprocess
p = subprocess.Popen(['tail','-10','/tmp/hosts.txt'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)

stdout,stderr = p.communicate()
print 'stdout : ',stdout
print 'stderr : ',stder

popen调用的时候会在父进程和子进程建立管道,然后我们可以把子进程的标准输出和错误输出都重定向到管道,然后从父进程取出。上面的communicate会一直阻塞,直到子进程跑完。这种方式是不能及时获取子程序的stdout和stderr。
还有一种方案,就是可以获取实时的输出信息

p = subprocess.Popen("/etc/service/tops-cmos/module/hadoop/test.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
returncode = p.poll()
while returncode is None:
        line = p.stdout.readline()
        returncode = p.poll()
        line = line.strip()
        print line
print returncode

这里就是把错误输出重定向到PIPE对应的标准输出,也就是说现在stderr都stdout是一起的了,下面是一个while,poll回去不断查看子进程是否已经被终止,如果程序没有终止,就一直返回None,但是子进程终止了就返货状态码,甚至于调用多次poll都会返回状态码。上面的demo就是可以获取子进程的标准输出和标准错误输出。

发布了38 篇原创文章 · 获赞 30 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/github_37382319/article/details/104532764