python调用Linux脚本或者shell指令的几种方法
admin
2023-07-11 20:25:26
0

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



相关内容

热门资讯

OpenAI,正式组建机器人事... 人工智能(AI)领域巨头OpenAI发布公告,宣布大力扩张内部机器人事业部,正式全面切入硬件赛道,实...
星火空间完成近亿元Pre-A轮... 据星火空间消息,6月1日,合肥星火空间科技有限公司完成近亿元Pre-A轮融资。本轮融资由云泽资本和轨...
刚刚,宇树IPO闪电过会!王兴... 智东西 作者 | 许丽思 编辑 | 漠影 智东西6月1日报道,刚刚,宇树通过上交所上市委会议审议。 ...
京东工业发起百川计划 携手上游... 京东工业大模型生态发布会6月1日在北京举行,京东工业携手合作伙伴正式开启“百川计划”,从数据、模型、...
强脑科技预计今年机械手销量大涨... IT之家 6 月 2 日消息,据彭博社 2 日(今天)报道,强脑科技预计,随着中国人形机器人产业快速...
一图看懂差距!iPhone 1... 快科技6月2日消息,iPhone 18 Pro不同版本电池容量不同的相关话题冲上社交平台热搜榜,引发...
iPhone 18 Pro 或... 据科技狐,近日,知名爆料人 Sonny Dickson 分享了 iPhone 18 Pro 全套机模...
武契奇:不排除卸任总统后担任总... 塞尔维亚总统武契奇近期密集释放政坛人事与大选相关信号,明确无意在 2027 年总统任期届满后谋求连任...
6月新机夯到拉盘点,告诉你哪台... 现在这形势,手机升价是不可能躲得过的了,而且涨价期至少持续两年。那既然内存涨价躲不过,就只能选升级大...
伊朗公开已故最高领袖哈梅内伊安... 新华社德黑兰6月2日电 据伊朗伊斯兰共和国通讯社2日报道,根据伊朗已故最高领袖阿里·哈梅内伊生前遗愿...