![](/img/trans.png)
[英]How to mock a subprocess.check_call exception in python test
[英]How to capture return code for subprocess.check_call in Python
我有一个脚本正在执行 5 个不同的 shell 命令,我正在使用 subprocess.check_call subprocess.check_call()
来执行它们。 问题是我似乎无法弄清楚如何正确捕获和分析返回码。
根据文档The CalledProcessError object will have the return code in the returncode attribute.
,但我不明白如何访问它。 如果我说
rc = subprocess.check_call("command that fails")
print(rc)
它告诉我
subprocess.CalledProcessError:命令“失败的命令”返回非零退出状态 1
但我不知道如何仅捕获 1 的 integer output。
我想这一定是可行的?
每当subprocess.check_call
方法失败时,都会引发CalledProcessError
。 从文档:
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)
使用 arguments 运行命令。 等待命令完成。 如果返回码为零,则返回,否则引发 CalledProcessError。 CalledProcessError object 将在 returncode 属性中具有返回码。
您可能只需要 subprocess.run 或使用 try/except 块来处理 CalledProcessError
也许
rc = subprocess.run("some_cmd").returncode
或者
try
...
rc = subprocess.check_call("command that fails")
except CalledProcessError as error:
rc = error.returncode
使用check_call
您必须添加一个 try/except 块并访问异常。 使用subprocess.run
,您可以在没有 try/except 块的情况下访问结果。
import subprocess
try:
subprocess.check_call(["command", "that", "fails"])
except subprocess.CalledProcessError as e:
print(e.returncode)
或使用subprocess.run
:
result = subprocess.run(["command", "that", "fails"])
print(result.returncode)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.