在 python clickCLI 应用程序的上下文中,我想在上下文管理器中运行一个子命令,该子命令将在更高级别的命令中设置。怎么可能做到这一点click?我的伪代码看起来像:
import click
from contextlib import contextmanager
@contextmanager
def database_context(db_url):
try:
print(f'setup db connection: {db_url}')
yield
finally:
print('teardown db connection')
@click.group
@click.option('--db',default='local')
def main(db):
print(f'running command against {db} database')
db_url = get_db_url(db)
connection_manager = database_context(db_url)
# here come the mysterious part that makes all subcommands
# run inside the connection manager
@main.command
def do_this_thing()
print('doing this thing')
@main.command
def do_that_thing()
print('doing that thing')
这将被称为:
> that_cli do_that_thing
running command against local database
setup db connection: db://user:pass@localdb:db_name
doing that thing
teardown db connection
> that_cli --db staging do_this_thing
running command against staging database
setup db connection: db://user:pass@123.456.123.789:db_name
doing this thing
teardown db connection
编辑:请注意,上面的示例是为了更好地说明 缺少的功能而伪造的click,而不是我想特别解决这个问题。我知道我可以在所有命令中重复相同的代码并达到相同的效果,这在我的实际用例中已经做到了。我的问题正是关于我只能在主函数中做什么,它会在上下文管理器中运行所有透明的子命令。
12345678_0001
慕的地6264312
相关分类