简介

subprocess模块用来创建新的进程,连接到其stdin、stdout、stderr管道并获取它们的返回码。subprocess模块的出现是为了替代如下旧模块及函数:os.systemos.spawn*os.popen*popen2.*commands.*。强烈建议POSIX用户(Linux、BSD等)安装并使用较新的subprocess32模块,而不是Python 2.7自带的subprocess。

快捷函数

推荐用户使用callcheck_callcheck_output这三个快捷函数,在无法满足需求的时候才使用更高级的Popen接口。

call

subprocess.call(args, *, stdin= None, stdout = None, stderr = None, shell = False) 
运行由args参数提供的命令,等待命令执行结束并返回返回码。args参数由字符串形式提供且有多个命令参数时,需要提供shell=True参数:

res = subprocess.call('ls')
print 'res:', res

或者:

res = subprocess.call('ls -l', shell = True)
print 'res:', res

多个命令参数通过列表的形式提供时不需要提供shell=True参数:

res = subprocess.call(['ls', '-l'])
print 'res:', res

注意不要为stdout和stderr参数赋值subprocess.PIPE,如果子进程输出量较多会造成死锁,这两个参数可以赋值为subprocess.STDOUT打印到屏幕或者赋值为一个文件对象将输出写入文件:

//test.py
import subprocess as sp
sp.call('python run.py', shell = True, stdin=open('fake_input', 'r'), stdout=open('result', 'w'))
//run.py
i = int(raw_input("Input a number:"))
print "You input number:", i

运行test.py后result中内容为:

Input a number:You input number: 12

check_call

subprocess.check_call(args, *, stdin = None, stdout = None, stderr = None, shell = False) 
与call方法类似,不同在于如果命令行执行成功,check_call返回返回码0,否则抛出subprocess.CalledProcessError异常。 
subprocess.CalledProcessError异常包括returncode、cmd、output等属性,其中returncode是子进程的退出码,cmd是子进程的执行命令,output为None。

import subprocess
try:
res = subprocess.check_call(['ls', '('])
print 'res:', res
except subprocess.CalledProcessError, exc:
print 'returncode:', exc.returncode
print 'cmd:', exc.cmd
print 'output:', exc.output

执行结果:

ls: (: No such file or directory
returncode: 1
cmd: ['ls', '(']
output: None

注意:不要为stdout和stderr参数赋值为subprocess.PIPE

check_output

subprocess.check_output(args, *, stdin = None, stderr = None, shell = False, universal_newlines = False)

在子进程执行命令,以字符串形式返回执行结果的输出。如果子进程退出码不是0,抛出subprocess.CalledProcessError异常,异常的output字段包含错误输出:

import subprocess
try:
res = subprocess.check_output('ls xxx',
stderr = subprocess.STDOUT,
shell = True)
print 'res:', res
except subprocess.CalledProcessError, exc:
print 'returncode:', exc.returncode
print 'cmd:', exc.cmd
print 'output:', exc.output

执行结果:

returncode: 1
cmd: ls xxx
output: ls: xxx: No such file or directory

注意:不要为stderr参数赋值为subprocess.PIPE

Python subprocess- call、check_call、check_output的更多相关文章

  1. python中的进程、线程(threading、multiprocessing、Queue、subprocess)

    Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...

  2. python ConfigParser、shutil、subprocess、ElementTree模块简解

    ConfigParser 模块 一.ConfigParser简介ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.section 下面为类 ...

  3. Python自动化运维之9、模块之sys、os、hashlib、random、time&datetime、logging、subprocess

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

  4. Python常用模块 (2) (loging、configparser、json、pickle、subprocess)

    logging 简单应用 将日志打印到屏幕 import logging logging.debug('debug message') logging.info('info message') log ...

  5. Python 第五篇(下):系统标准模块(shutil、logging、shelve、configparser、subprocess、xml、yaml、自定义模块)

    目录: shutil logging模块 shelve configparser subprocess xml处理 yaml处理 自定义模块 一,系统标准模块: 1.shutil:是一种高层次的文件操 ...

  6. 【python】-- json & pickle、xml、requests、hashlib、shelve、shutil、configparser、subprocess

    json & pickle Python中用于序列化的两个模块 json     用于[字符串]和 [python基本数据类型] 间进行转换 pickle   用于[python特有的类型] ...

  7. Python学习日记(九)—— 模块二(logging、json&pickle、xml、requests、configparser、shutil、subprocess)

    logging模块 用于便捷记录日志且线程安全的模块(便捷的写文件的模块,不允许多个人同时操作文件) 1.单文件日志 import logging logging.basicConfig(filena ...

  8. python笔记-9(subprocess模块、面向对象、socket入门)

    一.subprocess 模块 1.了解os.system()与os.popen的区别及不足 1.1 os.system()可以执行系统指令,将结果直接输出到屏幕,同时可以将指令是否执行成功的状态赋值 ...

  9. (转载)python调用shell命令之os 、commands、subprocess

    linux系统下进入python交互式环境: 一.os 模块 1.1.os模块的exec方法簇: python交互界面中: In [1]: import os In [2]: os.exec os.e ...

随机推荐

  1. TensorFlow入门之MNIST样例代码分析

    这几天想系统的学习一下TensorFlow,为之后的工作打下一些基础.看了下<TensorFlow:实战Google深度学习框架>这本书,目前个人觉得这本书还是对初学者挺友好的,作者站在初 ...

  2. 【django基础之ORM,增删改查】

    一.定义 1.什么是ORM? ORM,即Object-Relational Mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候, ...

  3. Web项目开发中用到的缓存技术

    在WEB开发中用来应付高流量最有效的办法就是用缓存技术,能有效的提高服务器负载性能,用空间换取时间.缓存一般用来 存储频繁访问的数据 临时存储耗时的计算结果 内存缓存减少磁盘IO 使用缓存的2个主要原 ...

  4. APK反编译之一:基础知识—APK、Dalvik字节码和smali文件

    refs: APK反编译之一:基础知识http://blog.csdn.net/lpohvbe/article/details/7981386 APK反编译之二:工具介绍http://blog.csd ...

  5. Android ListView 几个重要属性

    Android ListView 几个重要属性http://blog.csdn.net/avenleft/article/details/7334060 android:transcriptMode= ...

  6. (转)教你完全理解IO流里的 read(),read(byte[]),read(byte[],int off,int len)以及write

    背景:对于IO部分,总是感觉很虚,不能很好的理解其中的要义,其实仔细分析,掌握其中的规律,一切都会看起来十分的自然. 1 理解 1.1 从头总结 长期以来,java中的InputStream Outp ...

  7. 设计模式之单例模式实现(C++)

    #ifndef SINGLETON_H #define SINGLETON_H #include <cassert> #include <memory> #include &l ...

  8. 重启电脑后,redis 6380端口关闭重启

    zb@zb-computer:/usr/local/redis/etc$ /usr/local/redis/bin/redis-server redis.6380.conf &[1] 3062 ...

  9. Ansible5:常用模块

    目录 ping模块 setup模块 file模块 copy模块 service模块 cron模块 yum模块 user模块与group模块 user模块 group示例 synchronize模块 f ...

  10. scrum敏捷开发重点介绍

    参考: http://www.scrumcn.com/agile/scrum-knowledge-library/scrum.html https://www.zhihu.com/question/3 ...