Search code examples
pythonazureazure-cli

Catching exit codes from submodules in python


I have a function that allows me to run az cli commands from within python. However, whenever I get a non-zero exit code, the entire process is being shut down, including my python job. This happens for instance when I try to look up a user that does not exist.

I tried to wrap the function call with a try-except block, but it does not work, the job still exits on its own. How can I catch exit-code 3 (missing resource according to the documentation) and continue after trying to run the az-cli command?

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)

Solution

  • Found the solution - when catching SystemExit specifically, we can catch the exit and handle it accordingly. From on the documentation:

    sys.exit([arg])

    Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

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