Python subprocess- call、check_call、check_output

简介

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

posted on 2018-02-24 18:26  林枫水湾湾  阅读(30136)  评论(0编辑  收藏  举报

导航