python模塊之subprocess
阿新 • • 發佈:2017-08-21
bytes pro pipe cnblogs 參數 python模塊 import 啟用 其中
一、subprocess的作用
subprocess是用於在程序中執行系統命令的模塊,利用的其中的Popen方法在主進程中開辟子進程去執行系統命令,它與os.system的不同在於它可以將執行結果返回而os.system直接將執行結果輸出到終端。
二、subprocess的使用
subprocess的Popen方法的第一個參數為字符串格式的系統命令,其余常用參數有shell是否啟用命令解釋器,stdout指定標準輸出位置,stderr指定標準錯誤輸出位置,需要註意的是返回的結果是bytes類型的數據需要轉碼之後才能正常看,轉碼編碼需要根據系統字符編碼決定。
importsubprocess res=subprocess.Popen(‘dir‘,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #執行dir命令,啟用命令解釋器,標準輸出到subprocess.PIPE,標準錯誤輸出到subprocess.PIPE print(res.stdout.read().decode(‘gbk‘)) #查看標準輸出內容 print(res.stderr.read().decode(‘gbk‘)) #查看標準錯誤內容
python模塊之subprocess