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