subprocess 進程使用

來源:互聯網
上載者:User

同步進程

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.