如何在评估 Click cli 函数后继续执行 Python 脚本?

Jet*_*Cao 5 python command-line-interface python-click

假设我在文件中定义了一个基本的 click CLI 命令cli.py

import click

@click.command()
@click.option('--test-option')
def get_inputs(test_option):
    return test_option
Run Code Online (Sandbox Code Playgroud)

然后是另一个模块脚本test_cli.py,我想从中使用上面定义的 CLI:

from cli import get_inputs

print('before calling get_inputs')
print(get_inputs())
print('after calling get_inputs')
Run Code Online (Sandbox Code Playgroud)

然后在命令行上:

$ python test_cli.py --test-option test123
before calling get_inputs
Run Code Online (Sandbox Code Playgroud)

因此,运行 Click 命令后,整个 Python 进程就完成了,即使在启动调用的脚本中该 Click 命令之后有要计算的语句和表达式,它们也不会被执行。我将如何实现这一目标?

Jet*_*Cao 7

实际上,Click 文档很好地解释了为什么会发生这种情况,以及如何更改这种行为。

默认情况下,所有命令都继承自BaseCommand,它定义了一个main方法,默认情况下sys.exit(),该方法在使用 成功完成后退出,并发出SystemExit异常。

要更改此行为,可以禁用此处记录的standalone_mode术语。

因此,对于我的问题中提供的示例,将包含get_inputs()调用的行更改为test_cli.pyfrom print(get_inputs())into print(get_inputs.main(standalone_mode=False)),然后从命令行调用脚本会给出所需的行为,如下所示:

$ python test_cli.py --test-option test123
before calling get_inputs
test123
after calling get_inputs
Run Code Online (Sandbox Code Playgroud)