? 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')