python中command執行shell命令腳本方法


在Python中有一個模塊commands也很容易做到以上的效果.
看一下三個函數:
1). commands.getstatusoutput(cmd)
用os.popen()執行命令cmd, 然后返回兩個元素的元組(status, result),其中 status為int類型,result為string類型。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'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM