简体   繁体   English

如何在 Python 中捕获 subprocess.check_call 的返回码

[英]How to capture return code for subprocess.check_call in Python

I have a script that is executing 5 different shell commands and I'm using subprocess.check_call() to execute them.我有一个脚本正在执行 5 个不同的 shell 命令,我正在使用 subprocess.check_call subprocess.check_call()来执行它们。 The problem is that I can't seem to figure out how to properly capture and analyze the return code.问题是我似乎无法弄清楚如何正确捕获和分析返回码。

According to the docs The CalledProcessError object will have the return code in the returncode attribute.根据文档The CalledProcessError object will have the return code in the returncode attribute. , but I don't understand how to access that. ,但我不明白如何访问它。 If I say如果我说

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

It tells me它告诉我

subprocess.CalledProcessError: Command 'command that fails' returned non-zero exit status 1 subprocess.CalledProcessError:命令“失败的命令”返回非零退出状态 1

But I can't figure out how to capture just the integer output of 1.但我不知道如何仅捕获 1 的 integer output。

I'd imagine this must be doable somehow?我想这一定是可行的?

Whenever the subprocess.check_call method fails is raises a CalledProcessError .每当subprocess.check_call方法失败时,都会引发CalledProcessError From the docs:从文档:

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

Run command with arguments.使用 arguments 运行命令。 Wait for command to complete.等待命令完成。 If the return code was zero then return, otherwise raise CalledProcessError.如果返回码为零,则返回,否则引发 CalledProcessError。 The CalledProcessError object will have the return code in the returncode attribute. CalledProcessError object 将在 returncode 属性中具有返回码。

You may just want subprocess.run or to use a try/except block to handle the CalledProcessError您可能只需要 subprocess.run 或使用 try/except 块来处理 CalledProcessError

perhaps也许

rc = subprocess.run("some_cmd").returncode

or或者

try
...
    rc = subprocess.check_call("command that fails")
except CalledProcessError as error:
    rc = error.returncode

With check_call you'll have to add a try/except block and access the exception.使用check_call您必须添加一个 try/except 块并访问异常。 With subprocess.run you can access the result without a try/except block.使用subprocess.run ,您可以在没有 try/except 块的情况下访问结果。

import subprocess

try:
    subprocess.check_call(["command", "that", "fails"])
except subprocess.CalledProcessError as e:
    print(e.returncode)

Or using subprocess.run :或使用subprocess.run

result = subprocess.run(["command", "that", "fails"])
print(result.returncode)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM