Python並行操作 - 父子進程 subprocess庫
作者:Vamei 出處:http://www.cnblogs.com/vamei 歡迎轉載,也請保留這段聲明。謝謝!
參考鏈接
http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html
父子進程的概念
一個進程可以fork自身,成為一個子進程,並讓子進程去exec另外一個程序
python中的子進程
python中通過subprocess包,來fork一個子進程,並運行一個外部程序
需思考的點
創建子進程後,父進程是否阻塞
函數返回什麽
returncode不為0時(說明不是子進程),父進程如何處理
簡單使用
subprocess.call()
父進程等待子進程完成
返回退出信息(returncode)
subprocess.check_call()
父進程等待子進程完成
返回0
會檢查退出信息(returncode),如果returncode不為0則拋出subprocess.CalledProcessError錯誤,該對象包含有returncode屬性,可用try...except...來檢查
subprocess.check_output()
父進程等待子進程完成
返回子進程向標準輸出的輸出結果
會檢查退出信息(returncode),如果returncode不為0則拋出subprocess.CalledProcessError錯誤,該對象包含有returncode屬性和output屬性,output屬性為標準輸出的輸出結果,同樣可用try...except...來檢查
簡單使用舉例
list傳參
將程序名ls和參數-l放在一個表中傳遞給subprocess.call()
rc = subprocess.call(["ls","-l"])
string傳參
先運行一個shell,再用shell來解釋整個字符串
一些shell的內建命令必須使用shell來運行
out = subprocess.call("ls -l", shell=True)
高級使用 - 子進程並行&文本流
subprocess.Popen類
__init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
Popen對象創建後,父進程不會自動等待子進程完成
child = subprocess.Popen(["ping","-c","5","www.google.com"])
child.pid - 子進程的pid
child.stdin - 子進程的stdin
child.stdout - 子進程的stdout
child.stderr - 子進程的stderr
child.wait() - 父進程等待子進程完成
child.poll() - 檢查子進程狀態
child.send_signal(sig) - 給子進程發送信號
child.kill() - 終止子進程
child.terminate() - 終止子進程,與kill相等
child.communicate(input=None) - 給予子進程stdin後,獲得子進程的輸出流,返回結果為元組類型(stdout,stderr)。需註意該方法會阻塞當前進程。
高級使用舉例
父子進程並行
child = subprocess.Popen(["ping","-c","5","www.google.com"])
print("parent process")
子進程stdout導向另一子進程stdin
child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
子進程等待當前進程輸入
child = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
child.communicate("vamei")
Python並行操作 - 父子進程 subprocess庫