【问题标题】:Catching exit codes from submodules in python从 python 中的子模块捕获退出代码
【发布时间】:2023-02-21 17:41:59
【问题描述】:

我有一个函数可以让我从 python 中运行 az cli 命令。但是,每当我得到一个非零退出代码时,整个进程都会被关闭,包括我的 python 作业。例如,当我尝试查找不存在的用户时,就会发生这种情况。

我试图用 try-except 块包装函数调用,但它不起作用,作业仍然自行退出。如何捕获退出代码 3(根据 documentation 缺少资源)并在尝试运行 az-cli 命令后继续?

import os
from azure.cli.core import get_default_cli



def az_cli(args_str):
    args = args_str.split()
    cli = get_default_cli()
    exit_code = cli.invoke(args, out_file=open(os.devnull, 'w'))
    print("exit_code", exit_code)
    if cli.result.result:
        return cli.result.result
    elif cli.result.error:
        return cli.result.error
    return True

try: 
    user_id = "some-id-129-x1201-312"
    response = az_cli(f"ad user show --id {user_id}")
    print("response", response)
except Exception as e: 
    print(e.args)

【问题讨论】:

    标签: python azure azure-cli


    【解决方案1】:

    找到了解决方案 - 当具体捕获 SystemExit 时,我们可以捕获出口并相应地处理它。来自documentation

    系统退出([arg])

    退出 Python。这是通过引发 SystemExit 异常来实现的,因此由 try 语句的 finally 子句指定的清理操作得到尊重,并且可以在外部级别拦截退出尝试。

    try:
        response = az_cli(f"ad user show --id {id}")
        print("response", response)
    except SystemExit as e:
        print(e.args)
        print(e.code)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2012-08-19
      • 2021-03-17
      • 1970-01-01
      • 2020-08-12
      • 2016-12-12
      相关资源
      最近更新 更多