import subprocess cmd = ('tail', '/tmp/test.log') sp = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE) if sp.wait() == 0: print 'exec command succussful.' else: print sp.stderr.read()
异步进程
import subprocess cmd = ('tail', '-f', '/tmp/test.log') sp = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE) while True: if sp.poll() is not None: print 'exec command completed.' else: print sp.stdout.readline()
进程通讯
sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdoutput,erroutput) = sp.communicate()
sp.communicate会一直等到进程退出,并将标准输出和标准错误输出返回,这样就可以得到子进程的输出了,上面,标准输出和标准错误输出是分开的,也可以合并起来,只需要将stderr参数设置为subprocess.STDOUT就可以了,这样子:
sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdoutput,erroutput) = sp.communicate()
如果你想一行行处理子进程的输出,也没有问题:
sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: buff = sp.stdout.readline() if buff == '' and sp.poll() != None: break else: print buff
sp=subprocess.Popen("longprint", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sp.wait()
longprint是一个假想的有大量输出的进程,那么在我的xp, Python2.5的环境下,当输出达到4096时,死锁就发生了。当然,如果我们用sp.stdout.readline或者sp.communicate 去清理输出,那么无论输出多少,死锁都是不会发生的。或者我们不使用管道,比如不做重定向,或者重定向到文件,也都是可以避免死锁的。