简介

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. BZOJ3522 [Poi2014]Hotel 【树形dp】

    题目链接 BZOJ3522 题解 就是询问每个点来自不同子树离它等距的三个点的个数 数据支持\(O(n^2)\),可以对每个距离分开做 设\(f[i][j]\)表示\(i\)的子树中到\(i\)距离为 ...

  2. 最新版的Android4.4.2 SDK无法下载解决

    http://hi.baidu.com/petercao2008/item/65362d2bdbddfacba5275a50 问题: Downloading ARM EABI v7a System I ...

  3. 解题:BZOJ 2818 GCD

    题面 转化一下题目,即是求$1$到$n$中对于某个素数$pri$使得$gcd(x*pri,y*pri)=pri$的$(x,y)$的数目 这样一来就可以考虑每个质数$pri$对答案的贡献,即为$1$到$ ...

  4. 【线性基/神仙题】P4151 [WC2011]最大XOR和路径

    Description 给定一个无向连通图,边有边权,求一个 \(1~\sim n\) 的路径,最大化边权的异或和.如果一条边经过多次则计算多次. Input 第一行是两个整数 \(n,m\) 代表点 ...

  5. shell 中的流程控制关键字

    if...else if [ $1x == "ab"x ]; then echo "you had enter ab" elif [ $1x == " ...

  6. 前缀、中缀、后缀表达式以及简单计算器的C++实现

    前缀表达式(波兰表达式).中缀表达式.后缀表达式(逆波兰表达式) 介绍 三种表达式都是四则运算的表达方式,用以四则运算表达式求值,即数学表达式的求解. 前缀表达式 前缀表达式是一种没有括号的算术表达式 ...

  7. HDU 3943 数位dp+二分

    K-th Nya Number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 125536/65536 K (Java/Others) ...

  8. Asp.Net使用加密cookie代替session验证用户登录状态 源码分享

    首先 session 和 cache 拥有各自的优势而存在.  他们的优劣就不在这里讨论了. 本实例仅存储用户id于用户名,对于多级权限的架构,可以自行修改增加权限字段   本实例采用vs2010编写 ...

  9. R爬虫实战1(学习)—基于RVEST包

    这里用Hadley Wickham开发的rvest包.再次给这位矜矜业业开发各种好用的R包的大神奉上膝盖. 查阅资料如下: rvest的github rvest自身的帮助文档 rvest + CSS ...

  10. 20145234黄斐《Java程序设计》第五周

    教材学习内容总结 第八章部分 - 异常处理 语法与继承架构 使用try...catch 首先要明确一点:Java中所有错误都会打包为对象 JVM会尝试执行try区块中的程序代码,如果发生错误,执行程序 ...