如何在 Python 中捕获 subprocess.check_call 的 return 代码

How to capture return code for subprocess.check_call in Python

我有一个脚本正在执行 5 个不同的 shell 命令,我正在使用 subprocess.check_call() 来执行它们。问题是我似乎无法弄清楚如何正确捕获和分析 return 代码。

根据文档 The CalledProcessError object will have the return code in the returncode attribute.,但我不知道如何访问它。如果我说

rc = subprocess.check_call("command that fails")
print(rc)

它告诉我

subprocess.CalledProcessError: Command 'command that fails' returned non-zero exit status 1

但我不知道如何只捕获 1 的整数输出。

我想这一定是可行的吧?

每当 subprocess.check_call 方法失败时都会引发 CalledProcessError。来自文档:

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

您可能只想 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)