Python調(diào)用系統(tǒng)命令的四種方法詳解(os.system、os.popen、commands、subprocess)
一、os.system方法
這個方法是直接調(diào)用標(biāo)準(zhǔn)C的system() 函數(shù),僅僅在一個子終端運行系統(tǒng)命令,而不能獲取命令執(zhí)行后的返回信息。
os.system(cmd)的返回值。如果執(zhí)行成功,那么會返回0,表示命令執(zhí)行成功。否則,則是執(zhí)行錯誤。
使用os.system返回值是腳本的退出狀態(tài)碼,該方法在調(diào)用完shell腳本后,返回一個16位的二進制數(shù),低位為殺死所調(diào)用腳本的信號號碼,高位為腳本的退出狀態(tài)碼。
os.system()返回值為0 linux命令返回值也為0。
os.system()返回值為256,十六位二進制數(shù)示為:00000001,00000000,高八位轉(zhuǎn)成十進制為 1 對應(yīng) linux命令返回值 1。
os.system()返回值為512,十六位二進制數(shù)示為:00000010,00000000,高八位轉(zhuǎn)成十進制為 2 對應(yīng) linux命令返回值 2。
import os result = os.system('cat /etc/passwd') print(result) # 0
二、os.popen方法
os.popen()方法不僅執(zhí)行命令而且返回執(zhí)行后的信息對象(常用于需要獲取執(zhí)行命令后的返回信息),是通過一個管道文件將結(jié)果返回。通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執(zhí)行的輸出。
import os result = os.popen('cat /etc/passwd') print(result.read())
三、commands模塊
import commands status = commands.getstatus('cat /etc/passwd') print(status) output = commands.getoutput('cat /etc/passwd') print(output) (status, output) = commands.getstatusoutput('cat /etc/passwd') print(status, output)
四、subprocess模塊
Subprocess是一個功能強大的子進程管理模塊,是替換os.system,os.spawn* 等方法的一個模塊。
當(dāng)執(zhí)行命令的參數(shù)或者返回中包含了中文文字,那么建議使用subprocess。
import subprocess res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # 使用管道 print res.stdout.read() # 標(biāo)準(zhǔn)輸出 for line in res.stdout.readlines(): print line res.stdout.close() # 關(guān)閉
五、總結(jié):
os.system:獲取程序執(zhí)行命令的返回值。
os.popen: 獲取程序執(zhí)行命令的輸出結(jié)果。
commands:獲取返回值和命令的輸出結(jié)果。
到此這篇關(guān)于Python調(diào)用系統(tǒng)命令的四種方法(os.system、os.popen、commands、subprocess)的文章就介紹到這了,更多相關(guān)Python調(diào)用系統(tǒng)命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
TensorFlow搭建神經(jīng)網(wǎng)絡(luò)最佳實踐
這篇文章主要為大家詳細(xì)介紹了TensorFlow搭建神經(jīng)網(wǎng)絡(luò)最佳實踐,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03Python函數(shù)參數(shù)基礎(chǔ)介紹及示例
在聲明函數(shù)的時候,一般會根據(jù)函數(shù)所要實現(xiàn)的功能來決定函數(shù)是否需要參數(shù)。在多數(shù)情況下,我們聲明的函數(shù)都會使用到參數(shù),這篇文章主要介紹了Python函數(shù)參數(shù)2022-08-08