1.commands.getoutput('shell command')
2.commands.getstatus('file')
3.commands.getstatusoutput('shell command')
分別講解:
一、commands.getoutput('shell command')
執行shell命令,返回結果(string類型)
import commands
commands.getoutput('pwd')
#/Users/admin/PycharmProjects/test
二、commands.getstatus('file')
該函數已被python丟棄,不建議使用,它返回 ls -ld file 的結果(String)(返回結果太奇怪了,難怪被丟棄)import commands
commands.getstatus('admin.tar')
#'-rw-rw-r-- 1 oracle oracle 829440 Jan 29 10:36 admin.tar'
三、commands.getstatusoutput('shell command')執行shell命令, 返回兩個元素的元組tuple(status, result),status爲int類型,result爲string類型。
cmd的執行方式是{ cmd ; } 2>&1, 故返回結果包含標準輸出和標準錯誤。這是用的最多的一個函數。
import commands
commands.getstatusoutput('pwd')
#(0, '/Users/admin/PycharmProjects/test')