Python 将subprocess.Popen stderr重定向到控制台
我正在使用subprocess.Popen执行make命令。但是当make失败时,我并没有从make得到确切的错误,而脚本只是继续运行。如何让脚本停止并准确地向控制台显示make命令的输出Python 将subprocess.Popen stderr重定向到控制台,python,Python,我正在使用subprocess.Popen执行make命令。但是当make失败时,我并没有从make得到确切的错误,而脚本只是继续运行。如何让脚本停止并准确地向控制台显示make命令的输出 def app(self, build, soc, target): command = "make BUILD=%s SOC=%s TARGET=%s" % (build, soc, target) subprocess.Popen(command.split(), shell=False,
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()
你能试着更换一下吗
subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
与:
并让我们知道打印输出是什么样子。您可以尝试替换:
subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
与:
并让我们知道打印的输出是什么样子。如果您希望make输出实际进入控制台,请不要对stdout/stderr使用
子流程管道。默认情况下,被调用的进程将使用Python进程的stdout/stderr句柄。在这种情况下,如果被调用的进程返回非零退出代码,则可以使用subprocess.check_call()
函数引发subprocess.CalledProcessError
:
subprocess.check_call(command.split())
但是,如果您需要捕获make输出以在脚本中使用,则可以使用类似的子流程。check_output()
函数:
try:
output = subprocess.check_output(command.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
output = e.output
# error handling here
请注意,这将stdout和stderr输出合并为一个值。如果单独需要它们,则需要将subprocess.Popen
构造函数与communicate()
方法结合使用,并手动检查Popen
对象的returncode
属性:
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
如果您希望make输出实际进入控制台,请不要对stdout/stderr使用subprocess.PIPE
。默认情况下,被调用的进程将使用Python进程的stdout/stderr句柄。在这种情况下,如果被调用的进程返回非零退出代码,则可以使用subprocess.check_call()
函数引发subprocess.CalledProcessError
:
subprocess.check_call(command.split())
但是,如果您需要捕获make输出以在脚本中使用,则可以使用类似的子流程。check_output()
函数:
try:
output = subprocess.check_output(command.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
output = e.output
# error handling here
请注意,这将stdout和stderr输出合并为一个值。如果单独需要它们,则需要将subprocess.Popen
构造函数与communicate()
方法结合使用,并手动检查Popen
对象的returncode
属性:
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
失败时会出现什么(与python相关的)错误?最简单的方法是尽可能使用python 3.4,并将对subprocess.popen()
的调用替换为subprocess.run()
。它以字符串列表的形式返回一个对象,该对象包含stdout和stderr的返回代码和结果。@Tom Dalton实际上,问题是它只会继续,不会引发异常。然后,在脚本的后面部分,它依赖于make命令的传递,这里是脚本失败时的情况。失败时会出现什么(与python相关的)错误?最简单的方法是尽可能使用python 3.4,并将对subprocess.popen()
的调用替换为subprocess.run()
。它以字符串列表的形式返回一个对象,该对象包含stdout和stderr的返回代码和结果。@Tom Dalton实际上,问题是它只会继续,不会引发异常。随后在脚本中,它依赖于make命令的传递,这里是脚本失败的时候。