python第三方庫系列之十--commands庫,python--commands

來源:互聯網
上載者:User

python第三方庫系列之十--commands庫,python--commands
    我們這次講的是利用commands模組執行Linux shell命令,當我們用Python寫營運指令碼時,經常需要執行linux shell的命令,Python中的commands模組專門用於調用Linux shell命令,並返回狀態和結果,下面是commands模組的3個主要函數:
1.commands.getoutput('shell command')
2.commands.getstatus('file')
3.commands.getstatusoutput('shell command')
分別講解:
一、commands.getoutput('shell command')
執行shell命令,返回結果(string類型)

import commandscommands.getoutput('pwd')#/Users/admin/PycharmProjects/test

二、commands.getstatus('file')

該函數已被python丟棄,不建議使用,它返回 ls -ld file 的結果(String)(返回結果太奇怪了,難怪被丟棄)
import commandscommands.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 commandscommands.getstatusoutput('pwd')#(0, '/Users/admin/PycharmProjects/test')


聯繫我們

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