python操作shell 脚本_python调用Linux脚本或者shell指令的几种方法

python如何调用脚本或者shell指令?

方法1:

os.system()

只得到命令成功与否的执行状态>>> 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:

os.popen

通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)>>> 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() 既可以输出执行成功与否的状态,也会输出执行结果

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 "", line 1, in 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值