python执行shell命令
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命令的更多相关文章
- python 执行shell命令
1.os模块中的os.system()这个函数来执行shell命令 1 2 3 >>> os.system('ls') anaconda-ks.cfg install.log i ...
- Python记录-python执行shell命令
# coding=UTF-8 import os def distcp(): nncheck = os.system('lsof -i:8020') dncheck = os.system('lsof ...
- C++/Php/Python 语言执行shell命令
编程中经常需要在程序中使用shell命令来简化程序,这里记录一下. 1. C++ 执行shell命令 #include <iostream> #include <string> ...
- python中执行shell命令行read结果
+++++++++++++++++++++++++++++ python执行shell命令1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如 ...
- python2.7执行shell命令
python学习——python中执行shell命令 2013-10-21 17:44:33 标签:python shell命令 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者 ...
- 「Python」6种python中执行shell命令方法
用Python调用Shell命令有如下几种方式: 第一种: os.system("The command you want"). 这个调用相当直接,且是同步进行的,程序需要阻塞并等 ...
- python中执行shell命令的几个方法小结
原文 http://www.jb51.net/article/55327.htm 最近有个需求就是页面上执行shell命令,第一想到的就是os.system, os.system('cat /proc ...
- python的subprocess模块执行shell命令
subprocess模块可以允许我们执行shell命令 一般来说,使用run()方法就可以满足大部分情况 使用run执行shell命令 In [5]: subprocess.run('echo &qu ...
- python中执行shell命令的几个方法小结(转载)
转载:http://www.jb51.net/article/55327.htm python中执行shell命令的几个方法小结 投稿:junjie 字体:[增加 减小] 类型:转载 时间:2014- ...
随机推荐
- for练习--凑法
static void Main14购物卡(string[] args) { //小明单位发了50元的购物卡,他到超市买洗化用品,一是牙刷(5元),二是香皂(2元),三是牙膏(10元)怎么可以正好把五 ...
- 常用WebService收集
尊重原著作:本文转载自http://www.cnblogs.com/tianguook/archive/2010/09/29/1838469.html 天气预报Web服务,数据来源于中国气象局Endp ...
- Linux编程C/C++
C/C++基本数据类型 C/C++语言有一组基本数据类型,对应于计算机的基本存储单元和使用这些单元去保存数据的一些常用方式. 基本数据类型如下: 上面表格中的类型是基本的C/C++数据类型,但是在C+ ...
- Android 模块化编程之引用本地的aar
转: http://www.stormzhang.com/android/2015/03/01/android-reference-local-aar/ 随着项目越来越多,代码的复用就变得异常重要,这 ...
- Redis深入学习(1)前言&Redis简介
前言 最近工作上使用到Redis,当然以前也使用过redis,win,linux上都使用过,不系统,不深入,仅是头痛医头,脚痛医脚,这里整理一下自己的笔记,一来方便自己记忆,二来对同行提供借鉴,不足错 ...
- linux自带有usb驱动,为什么还需要libusb呢
linux里的软件分为用户层和内核层两种.比如内核里编译了温度传感器的驱动,还得有lm-sensors在用户层负责解释处理内核递交出的数据.usb驱动是硬件驱动方面的东西,libusb是给应用软件开发 ...
- Delphi XE6 通过JavaScript API调用百度地图
参考昨天的内容,有朋友还是问如何调用百度地图,也是,谁让咱都在国内呢,没办法,你懂的. 首先去申请个Key,然后看一下百度JavaScript的第一个例子:http://developer.baidu ...
- jdk1.6,jdk1.7共存
当然可以,安装的时候记得选择不同的安装目录,安装好以后,可以在开发工具(如eclipse)中切换不同的编译环境和运行环境.其实只要安装eclipse就自带了jdk1.3-1.6的编译环境了. Mac下 ...
- 【原】win7下调整分区
由于装系统时硬盘分区极度不合理,导致现在装一些比较大的开发软件根本不能装,但是又不想重装系统调整分区,而且还不想让已有的文件受到一点伤害,毕竟数据无价啊.几番搜索后,发现了一款比较好用的硬盘管理软件 ...
- 迪杰斯特拉(Dijkstra)算法
# include <stdio.h> # define MAX_VERTEXES //最大顶点数 # define INFINITY ;//代表∞ typedef struct {/* ...