Bigger-Mai 养成计划,subprocess模块
subprocess模块是python从2.4版本开始引入的模块。主要用来取代 一些旧的模块方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通过子进程来执行外部指令,并通过input/output/error管道,获取子进程的执行的返回信息。
常用方法:
subprocess.call():执行命令,并返回执行状态,其中shell参数为False时,命令需要通过列表的方式传入,当shell为True时,可直接传入命令
示例如下:

>>> a = subprocess.call(['df','-hT'],shell=False)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot >>> a = subprocess.call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot
>>> print a
0

subprocess.check_call():用法与subprocess.call()类似,区别是,当返回值不为0时,直接抛出异常
示例:

>>> a = subprocess.check_call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot
>>> print a
0
>>> a = subprocess.check_call('dfdsf',shell=True)
/bin/sh: dfdsf: command not found
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127

subprocess.check_output():用法与上面两个方法类似,区别是,如果当返回值为0时,直接返回输出结果,如果返回值不为0,直接抛出异常。需要说明的是,该方法在python3.x中才有。
subprocess.Popen():
在一些复杂场景中,我们需要将一个进程的执行输出作为另一个进程的输入。在另一些场景中,我们需要先进入到某个输入环境,然后再执行一系列的指令等。这个时候我们就需要使用到suprocess的Popen()方法。该方法有以下参数:
args:shell命令,可以是字符串,或者序列类型,如list,tuple。
bufsize:缓冲区大小,可不用关心
stdin,stdout,stderr:分别表示程序的标准输入,标准输出及标准错误
shell:与上面方法中用法相同
cwd:用于设置子进程的当前目录
env:用于指定子进程的环境变量。如果env=None,则默认从父进程继承环境变量
universal_newlines:不同系统的的换行符不同,当该参数设定为true时,则表示使用\n作为换行符
示例1,在/root下创建一个suprocesstest的目录:
>>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root')
示例2,使用python执行几个命令:

import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')
obj.stdin.close() cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close() print cmd_out
print cmd_error

也可以使用如下方法:

import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n') out_error_list = obj.communicate()
print out_error_list

示例3,将一个子进程的输出,作为另一个子进程的输入:
import subprocess
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
out = child2.communicate()
其他方法:

import subprocess
child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)
child.poll() #检查子进程状态
child.kill() #终止子进程
child.send_signal() #向子进程发送信号
child.terminate() #终止子进程

Bigger-Mai 养成计划,subprocess模块的更多相关文章
- Python全栈之路----常用模块----subprocess模块
我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python ...
- subprocess模块 sys模块
常用模块学习—subprocess模块详解 要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用 ...
- 18 subprocess模块(跟操作系统交互)
1.基本概念介绍 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的, 每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本 ...
- 23-[模块]-subprocess模块
1.调用系统命令 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的 ...
- python重要模块之subprocess模块
python重要模块之subprocess模块 我们经常要通过python去执行系统的命令或者脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就相当于发起了一个新的进程, ...
- subprocess模块和logging模块
主要内容: 一.subprocess模块 二.logging模块 1️⃣ subprocess模块 三种执行命令的方法 subprocess.run(*popenargs, input=None, ...
- Web前端开发工程师养成计划【转载】
Web前端开发工程师养成计划(入门篇) 最原始的忠告:这个世界上有想法的人很多,但是有想法又能实现它的人太少! 首先要感谢伟大的Web2.0概念.产品概念.用户体验概念.jQuery插件,是它们在中国 ...
- python学习道路(day7note)(subprocess模块,面向对象)
1.subprocess模块 因为方法较多我就写在code里面了,后面有注释 #!/usr/bin/env python #_*_coding:utf-8_*_ #linux 上调用python脚 ...
- subprocess模块
subprocess的目的就是启动一个新的进程并且与之通信. subprocess模块中只定义了一个类: Popen.可以使用Popen来创建进程,并与进程进行复杂的交互.它的构造函数如下: subp ...
随机推荐
- Web开发(调试方法 F12)
参考: 参考:MDN 调试HTML 参考:什么是浏览器开发者工具? 参考:检查和编辑页面与样式 工具参考:标记验证服务 工具参考:直接输入验证(直接输入HTML源码进行在线检查) 目录: 1.相关快捷 ...
- 关于parseInt()里的一些小坑
parseInt(string,radix)方法是将输入字符串转化为数值,两个输入参数中string为要转化的字符串,radix可省略,是浏览器以几进制来解读输入的string. 举几个例子就能够对该 ...
- 在linux服务器下JMeter如何执行jmx性能脚本
准备环境:linux平台.jmeter安装包. jdk 一. 安装jdk jdk的安装可以参考以下内容 http://jingyan.baidu.com/article ...
- leetcode 之 Two Sum II - Input array is sorted c++
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int ...
- ADB——keyevent命令
基本格式 adb shell input keyevent xxx # xxx为具体操作对应的数字 keycode 官方 KEYCODE 链接:戳这里 0 KEYCODE_UNKNOWN 未知按键 1 ...
- [py]python操作zookeeper
参考: https://blog.csdn.net/heizistudio/article/details/79568188 1.安装zookeeper zookeeper-3.4.6.tar.gz ...
- 【Pattern】-NO.150.Pattern.1 -【Pattern UML】
Style:Mac Series:Java Since:2018-09-10 End:2018-09-10 Total Hours:1 Degree Of Diffculty:5 Degree Of ...
- SQL Server创建存储过程——动态SQL
简介: 存储过程(stored procedure)是一组为了完成特定功能的SQL语句集合,经编译后存储在服务器端的数据库中,利用存储过程可以加速SQL语句的执行. 自定义存储过程,由用户创建并能完成 ...
- Firefox 安装 Adobe Flashplayer
3. 安装Adobe Flash Player: Adobe Flash Player的安装比较容易,只要将对应的文档复制到正确的的位置即可,具体的操作 如下: (1) 将libflashplayer ...
- Python实现图像边缘检测算法
title: "Python实现图像边缘检测算法" date: 2018-06-12T17:06:53+08:00 tags: ["图形学"] categori ...