2016-10-12 86 views
0

我正在使用subprocess.Popen执行make命令。但是当make失败时,我并没有从make中得到确切的错误,只是继续运行。如何获得脚本停止和显示控制台make命令将subprocess.Popen stderr重定向到控制台

def app(self, build, soc, target): 
    command = "make BUILD=%s SOC=%s TARGET=%s" % (build, soc, target) 
    subprocess.Popen(command.split(), shell=False, 
           stdout=subprocess.PIPE, 
           stderr=subprocess.PIPE).communicate() 
+0

什么(蟒蛇相关的)错误你得到,当它失败了呢? –

+0

如果可能,最简单的方法是使用Python 3.4,并用'subprocess.run()'将调用替换为'subprocess.popen()'。它返回一个包含stdout和stderr的返回码和结果作为字符串列表的对象。 –

+0

@Tom Dalton其实问题是它只是继续,并没有抛出异常。然后在脚本中,它依赖于make命令传递,这里是脚本失败的时候。 – homeGrown

回答

2

的准确输出,你可以尝试更换:

subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 

有:

p = subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
print p.communicate() 
print p.returncode 

让我们知道打印输出的样子。

0

如果您想让make输出真正进入控制台,请不要使用subprocess.PIPE作为stdout/stderr。默认情况下,被调用的进程将使用Python进程的stdout/stderr句柄。在这种情况下,你可以使用subprocess.check_call()功能提出一个subprocess.CalledProcessError如果被叫返回一个非零的退出代码:

subprocess.check_call(command.split()) 

但是,如果您需要捕获使用的化妆输出在你的脚本,你可以使用类似subprocess.check_output()功能:

try: 
    output = subprocess.check_output(command.split(), stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as e: 
    output = e.output 
    # error handling here 

注意,这结合了输出和错误输出到一个单一的值。如果单独需要的话,你就需要使用subprocess.Popen构造结合.communicate()方法和手动检查returncode属性Popen对象:

p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, 
     stderr=subprocess.PIPE) 
out, err = p.communicate() 
if p.returncode != 0: 
    # raise exception or other error handling here 
相关问题