同步進程
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 去清理輸出,那麼無論輸出多少,死結都是不會發生的。或者我們不使用管道,比如不做重新導向,或者重新導向到檔案,也都是可以避免死結的。