python調用Linux腳本或者shell指令的幾種方法

python如何調用腳本或者shell指令?python

方法1:
mysql

os.system()sql

只獲得命令成功與否的執行狀態shell

>>> 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   #返回狀態碼是0,表示shell執行成功
0


方法2:bash

os.popenpython2.7

經過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操做能夠看到執行的輸出。可是沒法讀取程序執行的返回值)ide

>>> 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() this

commands.getstatusoutput() 既能夠輸出執行成功與否的狀態,也會輸出執行結果spa

commands.getoutput() 只輸出執行結果

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

當命令調用錯誤時:

>>> (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經過子進程來執行外部指令,並經過input/output/error管道,獲取子進程的執行的返回信息


(1)subprocess.call執行命令,並返回狀態,相似os.system(),shell=True能夠直接調用命令,而shell=False命令和參數須要分開

>>> 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()相似,區別是,當返回值不爲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()

在一些複雜場景中,咱們須要將一個進程的執行輸出做爲另外一個進程的輸入。在另外一些場景中,咱們須要先進入到某個輸入環境,而後再執行一系列的指令等。這個時候咱們就須要使用到suprocess.Popen()方法。該方法有如下參數:

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

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

shell:True或False

cwd:用於設置子進程的當前目錄

env:用於指定子進程的環境變量。若是env=None,則默認從父進程繼承環境變量

universal_newlines:不一樣系統的的換行符不一樣,當該參數設定爲true時,則表示使用\n做爲換行符


如:在/usr/local/mysql下建立一個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,不會把輸出結果返回到顯示屏上

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

封裝一個函數:功能是調用系統命令:

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

輸出結果:
>>> print f1('ls')
(0, 'tb.txt\ntest2.py\ntest.py\n')
>>> print f1('lll')
(127, '/bin/sh: lll: command not found\n')
相關文章
相關標籤/搜索