Skip to content

Command Results

Sean Collings edited this page Jul 15, 2021 · 1 revision

arc allows for several differnt patterns for command results.

Result pattern

This is a pattern similar to Rust's result pattern. For most applications, this is preferred.

Example

from arc import CLI, Result, Ok, Err

cli = CLI()


@cli.subcommand()
def pick_a_number(val: int) -> Result[int, str]:
    if val == 1:
        return Ok(val)
    return Err("Not a good number :(")

cli()

Given a value of 1, this command will complete successfully. Given anything else, an exception will be logged and a system exit will be triggered.

$ python example.py pick-a-number val=333
ERROR: Not a good number :(

Exception Pattern

If you'd rather use exceptions, that's also acceptable. Arc provides an ExecutionError exception class, but arc will catch any error for you. This pattern is useful when an exception may occur somewhere deep in your application and you don't want to manually bubble a Result object.

Example

from arc import CLI, ExecutionError

cli = CLI()


@cli.subcommand()
def pick_a_number(val: int):
    if val == 1:
        return val
    raise ExecutionError("Not a good number :(")


cli()
$ python example.py pick-a-number val=333
ERROR: Not a good number :(

Handling Results Manually

In the above examples, either Err results or raised exceptions results in a system exit. You can take more fine-grain control over this via arguments to cli()

Handling Exceptions

arc's internal error handler can be disabled with handle_exception. Note that this will handle any exception that arc raises, not just ones raised inside of a command.

try:
    cli(handle_exception=False)
except SomeException as e:
    handle_exception(e)

Checking results

arc's internal result checker can be disabled with check_result.

result = cli(check_result=False)
print(result) # Would be something like Ok(1) or Err("Some error message")

Clone this wiki locally