subprocess是py2.4引入的功能,可以代替一些老旧的模块与功能:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
优先考虑使用call方法,如果call不满足需求,可以使用更底层的Popen
接口。
call
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
call方法会执行args指定的命令,等命令完成后,返回一个returncode
。
用法
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True) # 不建议使用shell=True的这种方法。
1
不要在call中使用stdout=PIPE或stderr=PIPE,这样可能会导致死锁,可以使用Popen
的communicate()方法进行管道操作。
check_call
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
和call方法一样,不同的是当返回值非0时会抛出CalledProcessError异常。
check_output
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
返回命令输出的字节序列,如果返回值非0,会抛出CalledProcessError异常。