python-commands模組

來源:互聯網
上載者:User

標籤:在營運中學習之python -commands模組

通過import commands模組 可以直接使用shell中的命令

(後期會慢慢補充,今天用到了貼出來搭建看一下)

要獲得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執行的結果.


看一下這些函數使用的例子:

>>> importcommands>>>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‘


python-commands模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.