簡介
subprocess模塊用來創建新的進程,連接到其stdin、stdout、stderr管道並獲取它們的返回碼。subprocess模塊的出現是為了替代如下舊模塊及函數:os.system
、os.spawn*
、os.popen*
、popen2.*
、commands.*
。強烈建議POSIX用戶(Linux、BSD等)安裝並使用較新的subprocess32模塊,而不是Python 2.7自帶的subprocess。
快捷函數
推薦用戶使用call
、check_call
和check_output
這三個快捷函數,在無法滿足需求的時候才使用更高級的Popen接口。
call
subprocess.call(args, *, stdin= None, stdout = None, stderr = None, shell = False)
運行由args參數提供的命令,等待命令執行結束並返回返回碼。args參數由字符串形式提供且有多個命令參數時,需要提供shell=True
參數:
res = subprocess.call('ls') print 'res:', res
或者:
res = subprocess.call('ls -l', shell = True) print 'res:', res
多個命令參數通過列表的形式提供時不需要提供shell=True參數:
res = subprocess.call(['ls', '-l']) print 'res:', res
注意不要為stdout和stderr參數賦值subprocess.PIPE
,如果子進程輸出量較多會造成死鎖,這兩個參數可以賦值為subprocess.STDOUT
打印到屏幕或者賦值為一個文件對象將輸出寫入文件:
//test.py
import subprocess as sp sp.call('python run.py', shell = True, stdin=open('fake_input', 'r'), stdout=open('result', 'w'))
//run.py i = int(raw_input("Input a number:")) print "You input number:", i
運行test.py
后result中內容為:
Input a number:You input number: 12
check_call
subprocess.check_call(args, *, stdin = None, stdout = None, stderr = None, shell = False)
與call方法類似,不同在於如果命令行執行成功,check_call返回返回碼0,否則拋出subprocess.CalledProcessError
異常。 subprocess.CalledProcessError
異常包括returncode、cmd、output等屬性,其中returncode是子進程的退出碼,cmd是子進程的執行命令,output為None。
import subprocess try: res = subprocess.check_call(['ls', '(']) print 'res:', res except subprocess.CalledProcessError, exc: print 'returncode:', exc.returncode print 'cmd:', exc.cmd print 'output:', exc.output
執行結果:
ls: (: No such file or directory returncode: 1 cmd: ['ls', '('] output: None
注意:不要為stdout和stderr參數賦值為subprocess.PIPE
。
check_output
subprocess.check_output(args, *, stdin = None, stderr = None, shell = False, universal_newlines = False)
在子進程執行命令,以字符串形式返回執行結果的輸出。如果子進程退出碼不是0,拋出subprocess.CalledProcessError異常,異常的output字段包含錯誤輸出:
import subprocess try: res = subprocess.check_output('ls xxx', stderr = subprocess.STDOUT, shell = True) print 'res:', res except subprocess.CalledProcessError, exc: print 'returncode:', exc.returncode print 'cmd:', exc.cmd print 'output:', exc.output
執行結果:
returncode: 1 cmd: ls xxx output: ls: xxx: No such file or directory
注意:不要為stderr參數賦值為subprocess.PIPE
。