【问题标题】:How to capture return code for subprocess.check_call in Python如何在 Python 中捕获 subprocess.check_call 的返回码
【发布时间】:2020-05-24 19:28:55
【问题描述】:

我有一个脚本正在执行 5 个不同的 shell 命令,我正在使用 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 的整数输出。

我想这一定是可行的?

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    使用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)
    

    【讨论】:

    • 我错过了as e: 位,这完美地解释了它。感谢您和@MindOfMetalAndWheels 的帮助。
    【解决方案2】:

    只要subprocess.check_call 方法失败,就会引发CalledProcessError。来自文档:

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

    运行带有参数的命令。等待命令完成。如果 返回代码为零然后返回,否则引发 CalledProcessError。 CalledProcessError 对象将在 返回码属性。

    您可能只需要 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
    

    【讨论】:

    • 我实际上正在使用try/except,但是当我尝试说except CalledProcessorerror,然后在该块中说print rc时,它告诉我rc还没有被分配.
    • 它说rc 没有被分配,因为CalledProcessError 对象有返回码,check_call 没有分配给rc 因为它引发了异常
    • 除了 CalledProcessError as e: print(e.returncode)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2017-01-21
    • 2018-04-19
    • 2016-09-09
    • 2010-10-16
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多