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模块的更多相关文章

  1. Python全栈之路----常用模块----subprocess模块

    我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python ...

  2. subprocess模块 sys模块

    常用模块学习—subprocess模块详解 要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用 ...

  3. 18 subprocess模块(跟操作系统交互)

    1.基本概念介绍 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的, 每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本 ...

  4. 23-[模块]-subprocess模块

    1.调用系统命令 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的 ...

  5. python重要模块之subprocess模块

    python重要模块之subprocess模块 我们经常要通过python去执行系统的命令或者脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就相当于发起了一个新的进程, ...

  6. subprocess模块和logging模块

    主要内容: 一.subprocess模块 二.logging模块 1️⃣  subprocess模块 三种执行命令的方法 subprocess.run(*popenargs, input=None, ...

  7. Web前端开发工程师养成计划【转载】

    Web前端开发工程师养成计划(入门篇) 最原始的忠告:这个世界上有想法的人很多,但是有想法又能实现它的人太少! 首先要感谢伟大的Web2.0概念.产品概念.用户体验概念.jQuery插件,是它们在中国 ...

  8. python学习道路(day7note)(subprocess模块,面向对象)

    1.subprocess模块   因为方法较多我就写在code里面了,后面有注释 #!/usr/bin/env python #_*_coding:utf-8_*_ #linux 上调用python脚 ...

  9. subprocess模块

    subprocess的目的就是启动一个新的进程并且与之通信. subprocess模块中只定义了一个类: Popen.可以使用Popen来创建进程,并与进程进行复杂的交互.它的构造函数如下: subp ...

随机推荐

  1. docker的安装和升级

    1.删除docker sudo apt-get purge docker.io sudo rm -rf /etc/docker/ sudo apt-get autoremove 2. 安装docker ...

  2. python学习笔记1-基础知识

    # 0.输入输出 # print数值型直接输出计算结果 pirnt( + ) # 输出 + = # input输入(可在括号内加提示语句) name = input('please enter you ...

  3. Uva 12009 平方数尾数与自身同样 dfs 构造

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/qq574857122/article/details/25166611 题目链接:点击打开链接 题意 ...

  4. Java面试题和解答(三)

    1.这段代码大多数情况下运行正常,但是某些情况下会出问题.什么时候会出现什么问题?如何修正? public class MyStack { private List<String> lis ...

  5. note_The Top Risks of Requirements Engineering

    The risk is greatest at several points: 1. Overlooking a crucial requirement This one the greatest r ...

  6. adobe air for ios 应用完成appstore评论

    1,跳转到App Store:NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%d ...

  7. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'multipartResolver': Failed to introspect bean class [org.springframework.web.multipart.commons.CommonsMultipartR

    在用spring mvc 做文件上传的时候出现了这个问题(能看到这篇文章就说明你已经有了那两个包了) 错误:org.springframework.beans.factory.BeanCreation ...

  8. Fiddler抓包【2】_捕获设置

    1.Fiddler抓web网站请求 手动设置方法一:Tools--->WinINET Options--->连接--->局域网设置--->代理服务器勾选后“高级”---> ...

  9. 【论文速读】XiangBai_CVPR2018_Rotation-Sensitive Regression for Oriented Scene Text Detection

    XiangBai_CVPR2018_Rotation-Sensitive Regression for Oriented Scene Text Detection 作者和代码 caffe代码 关键词 ...

  10. 使用 dom4j 处理 xml (2)

    记录一些 xpath 的常规用法,备忘. //3.XPath 了解(用于在xml中选取元素,类似 jquery 选择器) //3.1 路径 Node node1 = root.selectSingle ...