subprocess是python在2.4引入的模块, 主要用来替代下面几个模块和方法:html
os.system
os.spawn*
os.popen*
popen2.*
commands.*python
能够参考PEP324: http://legacy.python.org/dev/peps/pep-0324/sql
这是一个用来调用外部命令的模块, 替代了一些旧的模块, 提供了更加友好统一的接口.shell
三个封装方法windows
使用下面三个方法的时候, 注意两个问题: 1. shell=True或False, 两种解析方式是不一样的 2. 注意PIPE的使用, 可能致使卡死缓存
subprocess.call 运行命令, 等待完成, 并返回returncode安全
subprocess.check_call 运行命令, 等待完成, 若是返回值为0, 则返回returncode, 不然抛出带有returncode的CalledPorcessError异常.oop
subprocess.check_output 和check_call相似, 会检查返回值是否为0, 返回stdout.性能
卡死常见的缘由spa
这个模块在使用的时候, 可能会出现子进程卡死或hang住的状况. 通常出现这种状况的是这样的用法.
import subprocess import shlex proc = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True) print proc.stdout.read()
这里的直接读取了Popen对象的stdout, 使用了subprocess.PIPE. 这种状况致使卡死的缘由是PIPE管道的缓存被充满了, 没法继续写入, 也没有将缓存中的东西读出来.
官方文档的提示(Popen.wait()方法的Warning)
This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.
为了解决这个问题, Popen有一个communicate方法, 这个方法会将stdout和stderr数据读入到内存, 而且会一直独到两个流的结尾(EOF). communicate能够传入一个input参数, 用来表示向stdin中写入数据, 能够作到进程间的数据通讯.
注意: 官方文档中提示, 读取的数据是缓存在内存中的, 因此当数据量很是大或者是无限制的时候, 不要使用communicate, 应该会致使OOM.
通常状况下, stdout和stderr数据量不是很大的时候, 使用communicate不会致使问题, 量特别大的时候能够考虑使用文件来替代PIPE, 例如stdout=open("stdout", "w")[参考1].
参考2中给出了另外一种解决的思路, 使用select来读取Popen的stdout和stderr中的数据, select的这种用法windows下是不支持的, 不过能够作到比较实时的读取数据.
Popen中的shell参数含义
官方文档中推荐shell=False, 这种方式更加安全, 咱们来看一下官方给出的例子.
>>> from subprocess import call >>> filename = input("What file would you like to display?\n") What file would you like to display? non_existent; rm -rf / # >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
上面这种命令拼写的方式会致使一个安全问题, 就是用户能够进行相似sql注入的shell注入, 删除整个系统的文件, 这个是极其危险的.
shell=False会屏蔽shell中的不少特性, 因此能够避免上述这种安全问题, 当须要暴露给用户去使用的时候, 尤为要注意上述的安全问题.
shell=True的时候就是按照shell的方式解析和运行的.
Popen的一些简单调优思路
有个bufsize的参数, 这个默认是0, 就是不缓存, 1表示行缓存, 其余正数表示缓存使用的大小, 负数-1表示是使用系统默认的缓存大小.
在运行性能遇到问题时, 多是缓存区未开启或者过小, 致使了子进程被卡住, 效率低下, 能够考虑配置为-1或4096.
须要实时读取stdout和stderr的, 能够查阅[参考2], 使用select来读取stdout和stderr流.
参考: