要獲得shell指令的輸出隻需要`cmd`就可以了,
需要得到指令執行的狀态則需要判斷$?的值, 在Python中有一個子產品commands也很容易做到以上的效果.
看一下三個函數:
1). commands.getstatusoutput(cmd)
用os.popen()執行指令cmd, 然後傳回兩個元素的元組(status, result). cmd執行的方式是{ cmd ; }
2>&1, 這樣傳回結果裡面就會包含标準輸出和标準錯誤.
2). commands.getoutput(cmd)
隻傳回執行的結果, 忽略傳回值.
3). commands.getstatus(file)
傳回ls -ld file執行的結果.
看一下這些函數使用的例子:
>>> import
commands
>>>
commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>>
commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>>
commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>>
commands.getoutput('ls /bin/ls')
'/bin/ls'
>>>
commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'