python中執行shell命令的幾個方法小結

來源:互聯網
上載者:User
最近有個需求就是頁面上執行shell命令,第一想到的就是os.system,
複製代碼 代碼如下:


os.system('cat /proc/cpuinfo')


但是發現頁面上列印的命令執行結果 0或者1,當然不滿足需求了。

嘗試第二種方案 os.popen()
複製代碼 代碼如下:


output = os.popen('cat /proc/cpuinfo')
print output.read()


通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程式執行的傳回值)

嘗試第三種方案 commands.getstatusoutput() 一個方法就可以獲得到傳回值和輸出,非常好用。
複製代碼 代碼如下:


(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output


Python Document 中給的一個例子,
複製代碼 代碼如下:


>>> 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'


最後頁面上還可以根據傳回值來顯示命令執行結果。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.