>> import os >>> os.system('free -m') &nbs..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python調(diào)用Linux腳本或者shell指令的幾種方法

發(fā)布時間:2020-07-06 14:03:21 來源:網(wǎng)絡(luò) 閱讀:1528 作者:Darren_Chen 欄目:編程語言

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

方法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 的對象,對其進行讀取 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

當命令調(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子進程(功能強大,最常使用的方式)

subprocess模塊是python從2.4版本開始引入的模塊。主要用來取代 一些舊的模塊方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通過子進程來執(zhí)行外部指令,并通過input/output/error管道,獲取子進程的執(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ū)別是,當返回值不為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ù)雜場景中,我們需要將一個進程的執(zhí)行輸出作為另一個進程的輸入。在另一些場景中,我們需要先進入到某個輸入環(huán)境,然后再執(zhí)行一系列的指令等。這個時候我們就需要使用到suprocess.Popen()方法。該方法有以下參數(shù):

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

stdin,stdout,stderr:分別表示程序的標準輸入,標準輸出及標準錯誤

shell:True或False

cwd:用于設(shè)置子進程的當前目錄

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

universal_newlines:不同系統(tǒ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

使用標準輸出stdout和標準錯誤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')

將一個子進程的輸出,作為另一個子進程的輸入,相當于管道,如: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')



向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI