這里介紹一下python執(zhí)行shell命令的四種方法:
- os模塊中的os.system()這個函數(shù)來執(zhí)行shell命令
os.system('ls')
注袱讹,這個方法得不到shell命令的輸出伏嗜。
- popen()#這個方法能得到命令執(zhí)行后的結(jié)果是一個字符串,要自行處理才能得到想要的信息。
import os
str = os.popen("ls").read()
a = str.split("\n")
for b in a:
print b
這樣得到的結(jié)果與第一個方法是一樣的。
- commands模塊#可以很方便的取得命令的輸出(包括標準和錯誤輸出)和執(zhí)行狀態(tài)位
import commands
a,b = commands.getstatusoutput('ls')
commands.getstatusoutput(cmd)返回(status,output)
commands.getoutput(cmd)只返回輸出結(jié)果
commands.getstatus(file)返回ls -ld file 的執(zhí)行結(jié)果字符串淌哟,調(diào)用了getoutput,不建議使用這個方法距淫。