python模塊之subprocess模塊級方法的使用
subprocess.run()
運行并等待args參數(shù)指定的指令完成,返回CompletedProcess實例。
參數(shù):(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)。除input, capture_output, timeout, check,其他參數(shù)與Popen構(gòu)造器參數(shù)一致。
capture_output:如果設(shè)置為True,表示重定向stdout和stderr到管道,且不能再傳遞stderr或stdout參數(shù),否則拋出異常。
input:input參數(shù)將作為子進(jìn)程的標(biāo)準(zhǔn)輸入傳遞給Popen.communicate()方法,必須是string(需要指定encoding或errors參數(shù),或者設(shè)置text為True)或byte類型。非None的input參數(shù)不能和stdin參數(shù)一起使用,否則將拋出異常,構(gòu)造Popen實例的stdin參數(shù)將指定為subprocess.PIPE。
timeout:傳遞給Popen.communicate()方法。
check:如果設(shè)置為True,進(jìn)程執(zhí)行返回非0狀態(tài)碼將拋出CalledProcessError異常。
# 源碼 def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs): if input is not None: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') kwargs['stdin'] = PIPE if capture_output: if ('stdout' in kwargs) or ('stderr' in kwargs): raise ValueError('stdout and stderr arguments may not be used ' 'with capture_output.') kwargs['stdout'] = PIPE kwargs['stderr'] = PIPE with Popen(*popenargs, **kwargs) as process: try: stdout, stderr = process.communicate(input, timeout=timeout) except TimeoutExpired: process.kill() stdout, stderr = process.communicate() raise TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr) except: # Including KeyboardInterrupt, communicate handled that. process.kill() # We don't call process.wait() as .__exit__ does that for us. raise retcode = process.poll() if check and retcode: raise CalledProcessError(retcode, process.args, output=stdout, stderr=stderr) return CompletedProcess(process.args, retcode, stdout, stderr)
python3.5版本前,call(), check_all(), checkoutput()三種方法構(gòu)成了subprocess模塊的高級API。
subprocess.call()
運行并等待args參數(shù)指定的指令完成,返回執(zhí)行狀態(tài)碼(Popen實例的returncode屬性)。
參數(shù):(*popenargs, timeout=None, **kwargs)。與Popen構(gòu)造器參數(shù)基本相同,除timeout外的所有參數(shù)都將傳遞給Popen接口。
調(diào)用call()函數(shù)不要使用stdout=PIPE或stderr=PIPE,因為如果子進(jìn)程生成了足量的輸出到管道填滿OS管道緩沖區(qū),子進(jìn)程將因不能從管道讀取數(shù)據(jù)而導(dǎo)致阻塞。
# 源碼 def call(*popenargs, timeout=None, **kwargs): with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise
subprocess.check_call()
運行并等待args參數(shù)指定的指令完成,返回0狀態(tài)碼或拋出CalledProcessError異常,該異常的cmd和returncode屬性可以查看執(zhí)行異常的指令和狀態(tài)碼。
參數(shù):(*popenargs, **kwargs)。全部參數(shù)傳遞給call()函數(shù)。
注意事項同call()
# 源碼 def check_call(*popenargs, **kwargs): retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
subprocess.check_output()
運行并等待args參數(shù)指定的指令完成,返回標(biāo)準(zhǔn)輸出(CompletedProcess實例的stdout屬性),類型默認(rèn)是byte字節(jié),字節(jié)編碼可能取決于執(zhí)行的指令,設(shè)置universal_newlines=True可以返回string類型的值。
如果執(zhí)行狀態(tài)碼非0,將拋出CalledProcessError異常。
參數(shù):(*popenargs, timeout=None, **kwargs)。全部參數(shù)傳遞給run()函數(shù),但不支持顯示地傳遞input=None繼承父進(jìn)程的標(biāo)準(zhǔn)輸入文件句柄。
要在返回值中捕獲標(biāo)準(zhǔn)錯誤,設(shè)置stderr=subprocess.STDOUT;也可以將標(biāo)準(zhǔn)錯誤重定向到管道stderr=subprocess.PIPE,通過CalledProcessError異常的stderr屬性訪問。
# 源碼 def check_output(*popenargs, timeout=None, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs and kwargs['input'] is None: # Explicitly passing input=None was previously equivalent to passing an # empty string. That is maintained here for backwards compatibility. kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b'' return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, **kwargs).stdout
subprocess模塊還提供了python2.x版本中commands模塊的相關(guān)函數(shù)。
subprocess.getstatusoutput(cmd)
實際上是調(diào)用check_output()
函數(shù),在shell中執(zhí)行string類型的cmd指令,返回(exitcode, output)
形式的元組,output(包含stderr
和stdout
)是使用locale encoding解碼的字符串,并刪除了結(jié)尾的換行符。
# 源碼 try: data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT) exitcode = 0 except CalledProcessError as ex: data = ex.output exitcode = ex.returncode if data[-1:] == '\n': data = data[:-1] return exitcode, data
subprocess.getoutput(cmd)
與getstatusoutput()
類似,但結(jié)果只返回output。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用python處理題庫表格并轉(zhuǎn)化為word形式的實現(xiàn)
這篇文章主要介紹了使用python處理題庫表格并轉(zhuǎn)化為word形式的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04python中用matplotlib畫圖遇到的一些問題及解決
這篇文章主要介紹了python中用matplotlib畫圖遇到的一些問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09淺談Django自定義模板標(biāo)簽template_tags的用處
這篇文章主要介紹了淺談Django自定義模板標(biāo)簽template_tags的用處,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12Python實現(xiàn)刪除Android工程中的冗余字符串
這篇文章主要介紹了Python實現(xiàn)刪除Android工程中的冗余字符串,本文實現(xiàn)的是刪除Android資源(語言)國際化機(jī)制中的一些冗余字符串,需要的朋友可以參考下2015-01-01手把手教你如何使python變?yōu)榭蓤?zhí)行文件
對于exe可執(zhí)行文件,相信大家都不陌生,下面這篇文章主要給大家介紹了關(guān)于如何使python變?yōu)榭蓤?zhí)行文件的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02Python報錯no?module?named?torch的幾種原因及解決方案
這篇文章主要給大家介紹了關(guān)于Python報錯no?module?named?torch的幾種原因及解決方案,這是小白時常犯的錯,這個報錯一般說明在你電腦當(dāng)前環(huán)境下沒有安裝torch這個模塊,但也有其他情況,需要的朋友可以參考下2023-10-10