使用subprocess.check_call时CalledProcessError.stderr始终为None的问题
解决subprocess.check_call无法捕获stderr到异常对象的问题
问题原因
subprocess.check_call 抛出的 CalledProcessError 异常默认不会包含 stderr 内容——该函数的实现仅将返回码和命令信息传入异常,并未捕获并保存 stderr 输出,即便你设置了 stderr=subprocess.PIPE。
解决方法
方法1:改用subprocess.run(推荐)
使用 subprocess.run 并开启 check=True,它会在命令执行失败时抛出包含 stderr 属性的 CalledProcessError:
import subprocess import sys if '--fail' in sys.argv: print('this is the error message', file=sys.stderr) sys.exit(1) try: subprocess.run([sys.executable, sys.argv[0], '--fail'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, check=True) print('Not failed?') except subprocess.CalledProcessError as err: if err.stderr: print(err.stderr.decode()) else: print('<No error message>')
方法2:改用subprocess.check_output
check_output 原本用于捕获命令的 stdout,但只要设置 stderr=subprocess.PIPE,异常对象同样会包含 stderr 内容:
import subprocess import sys if '--fail' in sys.argv: print('this is the error message', file=sys.stderr) sys.exit(1) try: subprocess.check_output([sys.executable, sys.argv[0], '--fail'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) print('Not failed?') except subprocess.CalledProcessError as err: if err.stderr: print(err.stderr.decode()) else: print('<No error message>')
两种方法都能让你在异常中获取到目标程序输出的 stderr 内容。
内容的提问来源于stack exchange,提问作者Piotr Siupa
相关产品推荐
相关产品推荐

