這篇文章主要介紹python怎么調(diào)用subprocess模塊實(shí)現(xiàn)外部命令,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
直接給大家上實(shí)現(xiàn)代碼演示:
def run(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = p.communicate() print ('cmd=[{}] out=[{}] err=[{}] returncode=[{}]'.format(cmd, out, err, p.returncode)) if p.returncode != 0: raise Exception('cmd run error') return out
通過上述的實(shí)現(xiàn)代碼演示,我們可以直接調(diào)用run函數(shù)來運(yùn)行命令,得到命令的標(biāo)準(zhǔn)輸出,在返回碼非0的情況下,直接拋出異常。
以上是“python怎么調(diào)用subprocess模塊實(shí)現(xiàn)外部命令”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!