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
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 as exc:
print 'returncode:', exc.returncode
print 'cmd:', exc.cmd
print 'output:', exc.output
輸出: