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 commands
commands.getoutput('pwd')
#/Users/admin/PycharmProjects/test

二、commands.getstatus('file')

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章