转载:

https://www.cnblogs.com/thinker-lj/p/3860123.html

https://www.cnblogs.com/wenwangt/p/4897961.html

在python程序中调用shell命令,是件很酷且常用的事情……

1. os.system(command)

此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有执行内容,会在标准输出显示。这实际上是使用C标准库函数system()实现的。

缺点:这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。

实例:os.system('ls -l *')

2. os.popen(command,mode)

打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

实例:tmp = os.popen('ls -l *').readlines()

3. commands.getstatusoutput(command)

  使用os.popen()函数执行command命令并返回一个元组(status,output),分别表示command命令执行的返回状态和执行结果。对command的执行实际上是按照{command;} 2>&1的方式,所以output中包含控制台输出信息或者错误信息。output中不包含尾部的换行符。

4. subprocess模块

此模块在python2.4中初次亮相,其中集中了关于进程的诸多操作,其中的call()完全替代了system(),而popen()被更为丰富的Popen类替代;

总结:python提供了十分完善的调用shell命令的功能,在实战中,我碰到的问题,有system和popen基本可全部搞定;


1 os.system

可以返回运行shell命令状态,同时会在终端输出运行结果

例如 ipython中运行如下命令,返回运行状态status

os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40 passphrase=3 match=4 similar=deny random=47 enforce=everyone retry=3 Out[6]: 0

2 os.popen()

可以返回运行结果

popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

运行返回结果

In [20]: output = os.popen('cat /proc/cpuinfo')In [21]: lineLen = []In [22]: for line in output.readlines(): lineLen.append(len(line)) ....: In [23]: line line lineLen In [23]: lineLen Out[23]: [14, 25, ...

3 如何同时返回结果和运行状态,commands模块:

#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output. Interface summary: import commands outtext = commands.getoutput(cmd) (exitstatus, outtext) = commands.getstatusoutput(cmd) outtext = commands.getstatus(file) # returns output of "ls -ld file"  A trailing newline is removed from the output string. Encapsulates the basic operation: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close()

commands示例如下:

In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')In [25]: status
Out[25]: 0 In [26]: len(output) Out[26]: 3859

4 使用模块subprocess

通常项目中经常使用方法为subporcess.Popen, 我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

import subprocess
child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE) child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE) out = child2.communicate() print(out)

在例如使用lsblk查看swap分区的uuid:

import subprocesschild = subprocess.Popen(["lsblk", "-f"], stdout=subprocess.PIPE) out = child.stdout.readlines() swap_uuid = None for item in out: line = item.strip().split() if len(line) == 4: if(line[1] == 'swap'): swap_uuid = line[2] print(swap_uuid)

ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块

A more real-world example would look like this:try:retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e

相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:

4.1.1 subprocess.call()

父进程父进程等待子进程完成,返回exit code

4.1.2 subprocess.check_call()

父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查

4.1.3 subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查

例如:

In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--.  1 *** ***     366 May 26 09:10 ChangeLog

4.2.1

上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数

Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)

[wenwt@localhost syntax]$ rm subprocess.pyc
[wenwt@localhost syntax]$ python process.py
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms

加上wait方法:

[wenwt@localhost syntax]$ python process.py
PING www.google.com (173.194.219.103) 56(84) bytes of data.--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999msparent process

参考文章:Python标准库06 子进程 (subprocess包)

python 调用shell命令的方法相关推荐

  1. python调用shell命令

    在python程序中调用shell命令 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有 ...

  2. python调用shell命令-在Python中执行shell命令的6种方法,你都知道吗?

    原标题:在Python中执行shell命令的6种方法,你都知道吗? Python经常被称作"胶水语言",因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库.今天我们就讲解 ...

  3. python调用shell命令-「Python」6种python中执行shell命令方法

    用Python调用Shell命令有如下几种方式: 第一种: os.system("The command you want"). 这个调用相当直接,且是同步进行的,程序需要阻塞并等 ...

  4. python调用shell命令-Python调用shell命令常用方法(4种)

    方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未找到,该方法适用于shell命令 ...

  5. python调用shell命令-用Python调用Shell命令

    Python经常被称作"胶水语言",因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如 ...

  6. python 执行shell_用Python调用Shell命令

    Python经常被称作"胶水语言",因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如 ...

  7. python使用shell命令_python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情-- 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

  8. python 调用linux命令-Python调用shell命令常用方法

    Python调用shell指令 方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未 ...

  9. python调用linux命令的方法

    有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的.那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1. os 模块 ...

最新文章

  1. python下载不下来_Python不能下载zip文件,而Browser/Selenium可以下载,这是为什么?...
  2. BZOJ 3195: [Jxoi2012]奇怪的道路 | 状压DP
  3. android 更改edittext内容,Android如何实时更改edittext的内容
  4. 计算方法matlab编程徐萃薇,计算方法课程设计--用Newton插值多项式处理磁化曲线.docx...
  5. Java 注解知识总结
  6. Hibernate 原汁原味的四种抓取策略(转)
  7. CAD2010 为了保护_一文弄懂,锂电池的充电电路,以及它的保护电路方案设计
  8. Java执行系统命令策略
  9. SATA硬盘接口是什么
  10. tp3.2 URL模式
  11. linux 驱动移植实例,linux-2.6.22.6—驱动移植全记录
  12. 多个excel工作簿合并_如何使用Excel VBA将多个工作簿的全部工作表合并到一个工作簿中...
  13. arm开发板与PC通讯及访问外网
  14. python getch_python – 是否可以使用getch()来获取不同长度的输入?
  15. SQL UCASE() 函数、 LCASE() 函数
  16. html 查看excel表格,html展示excel表格数据-html读取本地excel文件并展示
  17. 生鲜配送小程序源码_生鲜配送小程序系统功能开发介绍(附带源码)
  18. 在iphone、ipad上安装一些常用命令行命令及实时抓取移动设备上的通信包(ADVsock2pipe+Wireshark+nc+tcpdump)
  19. 活动可视化怎么做?看京东乐高架构设计
  20. 互联网电商模式的迅速发展,消费返利模式你知道吗?

热门文章

  1. vue 定位所在地_vue系列教程之微商城项目|商品购买
  2. Linux 内核调试必备工具
  3. android 快速开发常用工具类,实例详解Android快速开发工具类总结
  4. GT Transceiver中的重要时钟及其关系(7)TXUSRCLK以及TXUSRCLK2的产生
  5. 【 MATLAB 】nextpow2 函数用法之 Optimize FFT with Padding
  6. perl dancer + net::ssh2监控服务器性能
  7. echarts实现动态传入数据刷新【可执行】
  8. 常用Intent调用(摘自网络)
  9. Docker Remote API v1.12使用
  10. Android Audio代码分析7 - stream type