利用os模塊
python調用Shell腳本,有三種方法:
- os.system(cmd)返回值是腳本的退出狀態碼
- os.popen(cmd)返回值是腳本執行過程中的輸出內容
- commands.getstatusoutput(cmd) 返回(status, output)
http://www.jb51.net/article/55327.htm
1. os.system(command)
此函數會啟動子進程,在子進程中執行command,並返回command命令執行完畢后的退出狀態,如果command有執行內容,會在標准輸出顯示。這實際上是使用C標准庫函數system()實現的。
缺點:這個函數在執行command命令時需要重新打開一個終端,並且無法保存command命令的執行結果。
實例:os.system('ls -l *')
2. os.popen(command,mode)
打開一個與command進程之間的管道。這個函數的返回值是一個文件對象,可以讀或者寫(由mode決定,mode默認是’r')。如果mode為’r',可以使用此函數的返回值調用read()來獲取command命令的執行結果。
os.system(cmd)或os.popen(cmd),前者返回值是腳本的退出狀態碼,后者的返回值是腳本執行過程中的輸出內容。實際使用時視需求情況而選擇。
output = os.popen('cat /proc/cpuinfo') print output.read()
tmp = os.popen('ls -l *').readlines()
3. commands.getstatusoutput(command)
- commands.getstatusoutput(cmd) 返回(status, output).
- commands.getoutput(cmd) 只返回輸出結果
- commands.getstatus(file) 返回ls -ld file的執行結果字符串,調用了getoutput,不建議使用此方法.
使用os.popen()函數執行command命令並返回一個元組(status,output),分別表示command命令執行的返回狀態和執行結果。對command的執行實際上是按照{command;} 2>&1的方式,所以output中包含控制台輸出信息或者錯誤信息。output中不包含尾部的換行符。
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo') print status, output
4. subprocess模塊
此模塊在python2.4中初次亮相,其中集中了關於進程的諸多操作,其中的call()完全替代了system(),而popen()被更為豐富的Popen類替代;
總結:python提供了十分完善的調用shell命令的功能,在實戰中,我碰到的問題,有system和popen基本可全部搞定;