15. python執(zhí)行shell cmd的4種方法

? 1. os.system(cmd)

? ? import os

? ? res = os.system(cmd)

##直接打印cmd執(zhí)行的信息,返回值是執(zhí)行命令的狀態(tài)碼,類似shell的$?

2. os.popen(cmd)

? import os

? res = os.popen('ls /home/work')

? print res.read().strip('\n') ##去除最后的空行,得到cmd直接輸出信息

? print res.readlines() ##將輸出信息轉(zhuǎn)成列表輸出,每個(gè)列表元素含'\n'結(jié)尾

3. subprocess模塊的Popen()產(chǎn)生新的process

Popen方法不會(huì)打印cmd執(zhí)行的信息,但有個(gè)缺陷,它是個(gè)阻塞的方法,若運(yùn)行cmd產(chǎn)生的內(nèi)容很多,函數(shù)易阻塞住。

from subprocess import Popen,PIPE

p = Popen("ls /home/work", shell=True, stdout=PIPE, stderr=PIPE)

print p.stdout.read().strip('\n') ##把最后一個(gè)空行去除,得到cmd輸出的直接信息

print p.stdout.readlines() ##將輸出信息轉(zhuǎn)成列表輸出,每個(gè)列表元素含'\n'結(jié)尾

print p.returncode

print p.pid

4. 使用commands.getstatusoutput(cmd)

這個(gè)方法也不打印cmd執(zhí)行的信息,也不是一個(gè)阻塞的方法,返回(status, output)元組

status, output = commands.getstatusoutput("ls /home/work")

或只獲得output或status

commands.getoutput('ls /home/work')

commands.getstatus('ls /home/work')


參考http://blog.csdn.net/menglei8625/article/details/7494094

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容