How to continue execution of Python script after evaluating a Click cli function?
Asked Answered
H

1

5

Say I have a basic click CLI command defined in a file cli.py:

import click

@click.command()
@click.option('--test-option')
def get_inputs(test_option):
    return test_option

Then another module script test_cli.py, from which I'd like to use the CLI defined in the above:

from cli import get_inputs

print('before calling get_inputs')
print(get_inputs())
print('after calling get_inputs')

Then on the command line:

$ python test_cli.py --test-option test123
before calling get_inputs

So it appears that after a Click command is ran, the entire Python process finishes, and even if there are statements and expressions to be evaluated after that Click command in the script that initiated the call, they will not be executed. How would I achieve this?

Hager answered 20/2, 2020 at 12:22 Comment(0)
H
7

Actually the Click documentation provides a good explanation for why this occurs, and how to change this behavior.

By default all commands inherit from BaseCommand, which defines a main method that by default exits upon successful completion with sys.exit(), which emits the SystemExit exception.

To change this behavior, one may disable what they term standalone_mode as documented here.

So for the example provided in my question, changing the line containing get_inputs() call in test_cli.py from print(get_inputs()) into print(get_inputs.main(standalone_mode=False)), then invoking the script from the command line gives the desired behavior, like so:

$ python test_cli.py --test-option test123
before calling get_inputs
test123
after calling get_inputs
Hager answered 20/2, 2020 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.