python第三方庫系列之十--commands庫
來源:程序員人生 發布時間:2014-12-07 10:07:56 閱讀次數:4152次
我們這次講的是利用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')
分別講授:
1、commands.getoutput('shell command')
履行shell命令,返回結果(string類型)
import commands
commands.getoutput('pwd')
#/Users/admin/PycharmProjects/test
2、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'
3、commands.getstatusoutput('shell command')
履行shell命令, 返回兩個元素的元組tuple(status, result),status為int類型,result為string類型。
cmd的履行方式是{ cmd ; } 2>&1, 故返回結果包括標準輸出和標準毛病。這是用的最多的1個函數。
import commands
commands.getstatusoutput('pwd')
#(0, '/Users/admin/PycharmProjects/test')
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈