? 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)成列表輸出,每個列表元素含'\n'結(jié)尾
3. subprocess模塊的Popen()產(chǎn)生新的process
Popen方法不會打印cmd執(zhí)行的信息,但有個缺陷瘤睹,它是個阻塞的方法,若運行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') ##把最后一個空行去除驴党,得到cmd輸出的直接信息
print p.stdout.readlines() ##將輸出信息轉(zhuǎn)成列表輸出瘪撇,每個列表元素含'\n'結(jié)尾
print p.returncode
print p.pid
4. 使用commands.getstatusoutput(cmd)
這個方法也不打印cmd執(zhí)行的信息,也不是一個阻塞的方法港庄,返回(status, output)元組
status, output = commands.getstatusoutput("ls /home/work")
或只獲得output或status
commands.getoutput('ls /home/work')
commands.getstatus('ls /home/work')