【问题标题】:How to continue execution of Python script after evaluating a Click cli function?评估 Click cli 函数后如何继续执行 Python 脚本?
【发布时间】:2020-06-04 18:32:31
【问题描述】:

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

import click

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

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

from cli import get_inputs

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

然后在命令行上:

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

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

【问题讨论】:

    标签: python command-line-interface python-click


    【解决方案1】:

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

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

    要改变这种行为,可以禁用他们将standalone_mode 称为documented here 的东西。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多