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 ...
随机推荐
- BZOJ 4753 [Jsoi2016]最佳团体 | 树上背包 分数规划
BZOJ 4753 [Jsoi2016]最佳团体 | 树上背包 分数规划 又是一道卡精度卡得我头皮发麻的题-- 题面(--蜜汁改编版) YL大哥是24OI的大哥,有一天,他想要从\(N\)个候选人中选 ...
- Xpack集成LDAP
支持两种配置方式: The ldap realm supports two modes of operation, a user search mode and a mode with specifi ...
- lumen 增加视图路径
在 ServiceProvider 里面加上 app('view')->addLocation(module_path('Develop') . '/resources/views');
- UVAL 7902 2016ECfinal F - Mr. Panda and Fantastic Beasts
题意: 给出n个串,求一个最短的第一个串的子串使它不在其他的n-1个串中出现,若有多个求字典序最小的. Limits: • 1 ≤ T ≤ 42. • 2 ≤ N ≤ 50000. • N ≤ S1 ...
- intval floatval
intval -- 获取变量的整数值 floatval -- 获取变量的浮点值 <?php $a = ; $b = ; $a/=$b; echo intval($a); echo floatva ...
- Docker图形界面管理之DockerUI
DockerUI DockerrUI是一个基于Docker API提供图形化页面简单的容器管理系统,支持容器管理.镜像管理. 1.1 下载镜像 docker pull abh1nav/dockerui ...
- linux常见故障一:linux 文件系统变只读
1. 重启系统看是否可以自动修复. 2. 使用fsck -y /dev/sda1 进行自动修复.(用”-y”选项来执行该命令对硬盘进行检查和修复) 添加参数:fsck -y -C -t ext3 ...
- fopen()、fwrite()、fread()函数使用说明与示例
fopen()函数: 1.作用: 在C语言中fopen()函数用于打开指定路径的文件,获取指向该文件的指针. 2.函数原型: FILE * fopen(const char * path,const ...
- ActiveMQ基本详解与总结& 消息队列-推/拉模式学习 & ActiveMQ及JMS学习
转自:https://www.cnblogs.com/Survivalist/p/8094069.html ActiveMQ基本详解与总结 基本使用可以参考https://www.cnblogs.co ...
- poj 1284 Primitive Roots (原根)
Primitive Roots http://poj.org/problem?id=1284 Time Limit: 1000MS Memory Limit: 10000K Descr ...