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 subprocess

child = 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 3999ms parent process

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

python执行shell命令的更多相关文章

  1. python 执行shell命令

    1.os模块中的os.system()这个函数来执行shell命令 1 2 3 >>> os.system('ls') anaconda-ks.cfg  install.log  i ...

  2. Python记录-python执行shell命令

    # coding=UTF-8 import os def distcp(): nncheck = os.system('lsof -i:8020') dncheck = os.system('lsof ...

  3. C++/Php/Python 语言执行shell命令

    编程中经常需要在程序中使用shell命令来简化程序,这里记录一下. 1. C++ 执行shell命令 #include <iostream> #include <string> ...

  4. python中执行shell命令行read结果

    +++++++++++++++++++++++++++++ python执行shell命令1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如 ...

  5. python2.7执行shell命令

    python学习——python中执行shell命令 2013-10-21 17:44:33 标签:python shell命令 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者 ...

  6. 「Python」6种python中执行shell命令方法

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

  7. python中执行shell命令的几个方法小结

    原文 http://www.jb51.net/article/55327.htm 最近有个需求就是页面上执行shell命令,第一想到的就是os.system, os.system('cat /proc ...

  8. python的subprocess模块执行shell命令

    subprocess模块可以允许我们执行shell命令 一般来说,使用run()方法就可以满足大部分情况 使用run执行shell命令 In [5]: subprocess.run('echo &qu ...

  9. python中执行shell命令的几个方法小结(转载)

    转载:http://www.jb51.net/article/55327.htm python中执行shell命令的几个方法小结 投稿:junjie 字体:[增加 减小] 类型:转载 时间:2014- ...

随机推荐

  1. 枚举基类Enum详解

    本文主要是对枚举类型的基类Enum类做一个介绍: 首先,Enum类位于java.lang包下,根据类的介绍可以发现,Enum类是Java中所有枚举类的父类,将枚举作为一个set或者Map的keys来使 ...

  2. WPF基础

    1.Sender 指的是被点击的控件.默认为object类. private void btnc1_Click(object sender, RoutedEventArgs e) { Button b ...

  3. html form表单提交数据并后台获取

    前台: HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器) <h ...

  4. 使用XmlReader读Xml

    XmlDocument和XElement在读取Xml时要将整个Xml文档放到内存中去操作,这样做操作简单,但是很费内存和IO(可能是磁盘IO或者网络IO):而在有些场景下我们必须考虑尽可能节省内存和I ...

  5. HTML5新属性

    1.contenteditable 属性指定元素内容是否可编辑. 注意: 当元素中没有设置 contenteditable 属性时,元素将从父元素继承. 所有主流浏览器都支持 contentedita ...

  6. Python之路第五天,基础(6)-模块

    模块 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个 ...

  7. C语言中内存分配 (转)

    在任何程序设计环境及语言中,内存管理都十分重要.在目前的计算机系统或嵌入式系统中,内存资源仍然是有限的.因此在程序设计中,有效地管理内存资源是程序员首先考虑的问题. 第1节主要介绍内存管理基本概念,重 ...

  8. SQL Server 数据库状态选项

    选项 1. single_user(单用户),multi_user(多用户),restricted_user(受限用户); 描述数据库的用户访问属性,它们互斥,设置其中任何一个选项就会取消对其它选项的 ...

  9. Today See>

    http://wenku.baidu.com/view/b08f3575f46527d3240ce061.html http://wenku.baidu.com/view/a3419558be2348 ...

  10. Qt学习--部件深入--烤猪蹄

    1,进程条--向用户显示程序的当前状态,向用户提示该任务需要多长时间才能够完成. Qt-ProgressBar创建进程条,QProgressBar,为了使进程条担当起进程指示功能,需要执行定义进程条的 ...