簡體   English   中英

如何在評估 Click cli 函數后繼續執行 Python 腳本?

[英]How to continue execution of Python script after evaluating a Click cli function?

假設我在文件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 命令之后要計算的語句和表達式,它們也不會被執行。 我將如何實現這一目標?

實際上,Click 文檔很好地解釋了為什么會發生這種情況,以及如何更改這種行為。

默認情況下,所有命令都繼承自BaseCommand ,它定義了一個main方法,該方法在成功完成后默認退出sys.exit() ,它會發出SystemExit異常。

要更改此行為,您可以禁用他們在此處記錄的稱為standalone_mode內容

因此,對於我的問題中提供的示例,將get_inputs()包含get_inputs()調用的test_cli.pyprint(get_inputs()) print(get_inputs.main(standalone_mode=False))print(get_inputs.main(standalone_mode=False)) ,然后從命令行調用腳本給出所需的行為,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM