简介

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. NOIP2018前的一些计划&记录(日更)

    先空着,等停课了再开始写. 诸位好,我是yyb.现在显然已经不再是高一的小蒟蒻了,已经升级为了高二的菜鸡了 现在已经不能再每天划划水切切题了,毕竟......已经高二了,所有的机会从高一的两倍全部除了 ...

  2. 观V8源码中的array.js,解析 Array.prototype.slice为什么能将类数组对象转为真正的数组?

    在官方的解释中,如[mdn] The slice() method returns a shallow copy of a portion of an array into a new array o ...

  3. sublime_Text3中snippet设置信息头(包括作者、日期)

    1.tool->new snippet(工具->新代码段) 创建一个新的snippet,并保存为author.sublime-snippet(最好在该目录(User)下再创建一个MySni ...

  4. Levenshtein Distance莱文斯坦距离算法来计算字符串的相似度

    Levenshtein Distance莱文斯坦距离定义: 数学上,两个字符串a.b之间的莱文斯坦距离表示为levab(|a|, |b|). levab(i, j) = max(i, j)  如果mi ...

  5. Docker图形界面管理之Portainer

    介绍 Portainer是一个开源.轻量级Docker管理用户界面,基于Docker API,可管理Docker主机或Swarm集群,支持最新版Docker和Swarm模式.官方文档 https:// ...

  6. Go_20: Golang 中 time 包的使用

    time包中包括两类时间:时间点(某一时刻)和时常(某一段时间) 1. 时间常量(时间格式化) const ( ANSIC = "Mon Jan _2 15:04:05 2006" ...

  7. 转:zookeeper中Watcher和Notifications

    转自:http://www.tuicool.com/articles/B7FRzm 传统polling远程service服务 传统远程的service往往是这样服务的,服务提供者在远程service注 ...

  8. 翻译: 星球生成 II

    翻译: 星球生成 II 本文翻译自Planet Generation - Part II 译者: FreeBlues 以下为译文: 概述 在前一章 我解释了如何为星球创建一个几何球体. 在本文中, 我 ...

  9. JavaScript 运行机制之执行顺序详解

    JavaScript是一种描述型脚本语言,它不同于 Java 或 C# 等编译性语言,它不需要进行编译成中间语言,而是由浏览器进行动态地解析与执行.如果你不能理解 JavaScript 语言的运行机制 ...

  10. Javascript的V8引擎研究

    1.针对上下文的Snapshot技术 什么是上下文(Contexts)?实际是JS应用程序的运行环境,避免应用程序的修改相互影响,例如一个页面js修改内置对象方法toString,不应该影响到另外页面 ...