Python subprocess- call、check_call、check_output
简介
subprocess模块用来创建新的进程,连接到其stdin、stdout、stderr管道并获取它们的返回码。subprocess模块的出现是为了替代如下旧模块及函数:os.system、os.spawn*、os.popen*、popen2.*、commands.*。强烈建议POSIX用户(Linux、BSD等)安装并使用较新的subprocess32模块,而不是Python 2.7自带的subprocess。
快捷函数
推荐用户使用call、check_call和check_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的更多相关文章
- python中的进程、线程(threading、multiprocessing、Queue、subprocess)
Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...
- python ConfigParser、shutil、subprocess、ElementTree模块简解
ConfigParser 模块 一.ConfigParser简介ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.section 下面为类 ...
- Python自动化运维之9、模块之sys、os、hashlib、random、time&datetime、logging、subprocess
python模块 用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需 ...
- Python常用模块 (2) (loging、configparser、json、pickle、subprocess)
logging 简单应用 将日志打印到屏幕 import logging logging.debug('debug message') logging.info('info message') log ...
- Python 第五篇(下):系统标准模块(shutil、logging、shelve、configparser、subprocess、xml、yaml、自定义模块)
目录: shutil logging模块 shelve configparser subprocess xml处理 yaml处理 自定义模块 一,系统标准模块: 1.shutil:是一种高层次的文件操 ...
- 【python】-- json & pickle、xml、requests、hashlib、shelve、shutil、configparser、subprocess
json & pickle Python中用于序列化的两个模块 json 用于[字符串]和 [python基本数据类型] 间进行转换 pickle 用于[python特有的类型] ...
- Python学习日记(九)—— 模块二(logging、json&pickle、xml、requests、configparser、shutil、subprocess)
logging模块 用于便捷记录日志且线程安全的模块(便捷的写文件的模块,不允许多个人同时操作文件) 1.单文件日志 import logging logging.basicConfig(filena ...
- python笔记-9(subprocess模块、面向对象、socket入门)
一.subprocess 模块 1.了解os.system()与os.popen的区别及不足 1.1 os.system()可以执行系统指令,将结果直接输出到屏幕,同时可以将指令是否执行成功的状态赋值 ...
- (转载)python调用shell命令之os 、commands、subprocess
linux系统下进入python交互式环境: 一.os 模块 1.1.os模块的exec方法簇: python交互界面中: In [1]: import os In [2]: os.exec os.e ...
随机推荐
- 【洛谷4005】小Y和地铁(搜索)
[洛谷4005]小Y和地铁(搜索) 题面 洛谷 有点长. 题解 首先对于需要被链接的两个点,样例中间基本上把所有的情况都给出来了. 但是还缺了一种从下面绕道左边在从整个上面跨过去在从右边绕到下面来的情 ...
- kafka问题集(三)ISR缺失
仅个人实践所得,若是有误,欢迎指出. 一.场景 kafka集群中某一节点(N-10)的CPU利用率大于整个集群的平均水平,且达到报警值.使用top命令后台查看时发现是kafka服务导致CPU利用率高. ...
- POJ.1067 取石子游戏 (博弈论 威佐夫博弈)
POJ.1067 取石子游戏 (博弈论 威佐夫博弈) 题意分析 简单的威佐夫博弈 博弈论快速入门 代码总览 #include <cstdio> #include <cmath> ...
- java多线程 -- 创建线程的第三者方式 实现Callable接口
Java 5.0 在 java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个 ...
- (转)Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences
除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息.其存储位置在/data ...
- 解题:POI 2007 Tourist Attractions
题面 事实上这份代码在洛谷过不去,因为好像要用到一些压缩空间的技巧,我并不想(hui)写(捂脸) 先预处理$1$到$k+1$这些点之间相互的最短路和它们到终点的最短路,并记录下每个点能够转移到时的状态 ...
- bashttpd使用手册
http://note.youdao.com/noteshare?id=15775dca9fcdc7326e80158082572ed5
- 3 Kafka两个版本在Zookeeper的元数据存储
0.8 [consumers, admin, config, controller, brokers, controller_epoch] 这些节点都归于谁管理 consumers: 0.8版本的客户 ...
- AAC音频格式详解
关于AAC音频格式基本情况,可参考维基百科http://en.wikipedia.org/wiki/Advanced_Audio_Coding AAC音频格式分析 AAC音频格式有ADIF和ADTS: ...
- 用rem做响应式开发
设置对应的响应式的html rem比例 rem就是根元素(即:html)的字体大小.html中的所有标签样式凡是涉及到尺寸的(如: height,width,padding,margin,font-s ...