python調(diào)用Linux腳本或者shell指令的幾種方法-創(chuàng)新互聯(lián)

python如何調(diào)用腳本或者shell指令?

成都創(chuàng)新互聯(lián)公司專業(yè)提供成都電信服務(wù)器托管服務(wù),為用戶提供五星數(shù)據(jù)中心、電信、雙線接入解決方案,用戶可自行在線購買成都電信服務(wù)器托管服務(wù),并享受7*24小時金牌售后服務(wù)。

方法1:

os.system()

只得到命令成功與否的執(zhí)行狀態(tài)

>>> import os >>> os.system('free -m')              total       used       free     shared    buffers     cached Mem:           474        463         11          0         13         29 -/+ buffers/cache:        420         54 Swap:         1023        415        608 >>> ret=os.system('free -m')              total       used       free     shared    buffers     cached Mem:           474        464         10          0         12         30 -/+ buffers/cache:        420         53 Swap:         1023        415        608 >>> print ret   #返回狀態(tài)碼是0,表示shell執(zhí)行成功 0

方法2:

os.popen

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

>>> import os >>> output = os.popen('free -mt') >>> print output.read()               total        used        free      shared  buff/cache   available Mem:           7823        3445         215          64        4162        3864 Swap:          3071         270        2801 Total:        10895        3716        3016

方法3:

commands.getstatusoutput() && commands.getoutput()

commands.getstatusoutput() 既可以輸出執(zhí)行成功與否的狀態(tài),也會輸出執(zhí)行結(jié)果

commands.getoutput() 只輸出執(zhí)行結(jié)果

>>> import commands >>> (status, output) = commands.getstatusoutput('free -mt') >>> print status 0 >>> print output               total        used        free      shared  buff/cache   available Mem:           7823        3475         188          64        4159        3834 Swap:          3071         270        2801 Total:        10895        3746        2989 >>> output = commands.getoutput('free -mt') >>> print output               total        used        free      shared  buff/cache   available Mem:           7823        3475         188          64        4159        3834 Swap:          3071         270        2801 Total:        10895        3746        2989

當(dāng)命令調(diào)用錯誤時:

>>> (status, output) = commands.getstatusoutput('free -aaa') >>> print status 256 >>> print output free: invalid option -- 'a' Usage: free [options] Options: -b, --bytes         show output in bytes -k, --kilo          show output in kilobytes -m, --mega          show output in megabytes -g, --giga          show output in gigabytes      --tera          show output in terabytes -h, --human         show human-readable output      --si            use powers of 1000 not 1024 -l, --lohi          show detailed low and high memory statistics -t, --total         show total for RAM + swap -s N, --seconds N   repeat printing every N seconds -c N, --count N     repeat printing N times, then exit -w, --wide          wide output      --help     display this help and exit -V, --version  output version information and exit For more details see free(1).

方法4:

subprocess子進(jìn)程(功能強(qiáng)大,最常使用的方式)

subprocess模塊是python從2.4版本開始引入的模塊。主要用來取代 一些舊的模塊方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通過子進(jìn)程來執(zhí)行外部指令,并通過input/output/error管道,獲取子進(jìn)程的執(zhí)行的返回信息。

(1)subprocess.call執(zhí)行命令,并返回狀態(tài),類似os.system(),shell=True可以直接調(diào)用命令,而shell=False命令和參數(shù)需要分開

>>> output = subprocess.call(['free','-mt'],shell=False)               total        used        free      shared  buff/cache   available Mem:           7823        3446         209          64        4167        3863 Swap:          3071         270        2801 Total:        10895        3716        3011 >>> print output 0 >>> output = subprocess.call('free -mt',shell=True)               total        used        free      shared  buff/cache   available Mem:           7823        3445         209          64        4167        3863 Swap:          3071         270        2801 Total:        10895        3716        3010 >>> print output 0

(2)subprocess.check_call 用法與subprocess.call()類似,區(qū)別是,當(dāng)返回值不為0時,還會拋出python層面的異常

>>> output = subprocess.call('la -ltrh',shell=True) /bin/sh: la: command not found >>> output = subprocess.check_call('la -ltrh',shell=True) /bin/sh: la: command not found Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib64/python2.7/subprocess.py", line 542, in check_call     raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'la -ltrh' returned non-zero exit status 127

(3)suprocess.Popen()

在一些復(fù)雜場景中,我們需要將一個進(jìn)程的執(zhí)行輸出作為另一個進(jìn)程的輸入。在另一些場景中,我們需要先進(jìn)入到某個輸入環(huán)境,然后再執(zhí)行一系列的指令等。這個時候我們就需要使用到suprocess.Popen()方法。該方法有以下參數(shù):

args:shell命令,可以是字符串,或者序列類型,如list,tuple。

stdin,stdout,stderr:分別表示程序的標(biāo)準(zhǔn)輸入,標(biāo)準(zhǔn)輸出及標(biāo)準(zhǔn)錯誤

shell:True或False

cwd:用于設(shè)置子進(jìn)程的當(dāng)前目錄

env:用于指定子進(jìn)程的環(huán)境變量。如果env=None,則默認(rèn)從父進(jìn)程繼承環(huán)境變量

universal_newlines:不同系統(tǒng)的的換行符不同,當(dāng)該參數(shù)設(shè)定為true時,則表示使用\n作為換行符

如:在/usr/local/mysql下創(chuàng)建一個suprocesstest的目錄:

>>> output = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/usr/local/mysql') >>> output = subprocess.Popen('ls -ld sub*',shell=True,cwd='/usr/local/mysql') drwxr-xr-x 2 mysqladmin dba 6 Mar  5 16:12 subprocesstest

使用標(biāo)準(zhǔn)輸出stdout和標(biāo)準(zhǔn)錯誤stderr,不會把輸出結(jié)果返回到顯示屏上

>>> child1 = subprocess.Popen('free -mt',shell=True) >>>               total        used        free      shared  buff/cache   available Mem:           7823        3446         204          64        4172        3863 Swap:          3071         270        2801 Total:        10895        3716        3006 >>> child1 = subprocess.Popen('free -mt',shell=True,stdout=subprocess.PIPE) >>> output = child1.communicate() >>> print output ('              total        used        free      shared  buff/cache   available\nMem:           7823        3446         201          64        4175        3862\nSwap:          3071         270        2801\nTotal:        10895        3717        3002\n', None) >>> child1 = subprocess.Popen('lss',shell=True,stdout=subprocess.PIPE) /bin/sh: lss: command not found >>> child1 = subprocess.Popen('lss',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> output = child1.communicate() >>> print output ('', '/bin/sh: lss: command not found\n')

將一個子進(jìn)程的輸出,作為另一個子進(jìn)程的輸入,相當(dāng)于管道,如:cat /etc/passwd|grep 'root'

>>> import subprocess >>> child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE) >>> child2 = subprocess.Popen(["grep","root"],stdin=child1.stdout, stdout=subprocess.PIPE) >>> output = child2.communicate() >>> print output ('root:x:0:0:root:/root:/bin/bash\noperator:x:11:0:operator:/root:/sbin/nologin\n', None)

封裝一個函數(shù):功能是調(diào)用系統(tǒng)命令:

import subprocess def f1(cmd):   a = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)   output = a.stdout.read()   code = a.wait()   return code, output print f1('ls') print f1('lll') 輸出結(jié)果: >>> print f1('ls') (0, 'tb.txt\ntest2.py\ntest.py\n') >>> print f1('lll') (127, '/bin/sh: lll: command not found\n')

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

網(wǎng)站欄目:python調(diào)用Linux腳本或者shell指令的幾種方法-創(chuàng)新互聯(lián)
分享鏈接:http://muchs.cn/article18/dpejgp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、搜索引擎優(yōu)化、手機(jī)網(wǎng)站建設(shè)、建站公司、軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營