Python subprocess模塊call&check_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

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

輸出:


詳情:https://www.cnblogs.com/hubavyn/p/8467329.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章