python 点击使用 standalone_mode

python click usage of standalone_mode

这个问题是关于 Python Click 库的。

我想点击收集我的命令行参数。收集时,我想重用这些值。我不想要任何疯狂的回调链接,只需使用 return 值。默认情况下,单击禁用 return 值并调用 sys.exit()

我想知道如何正确调用 standalone_mode (http://click.pocoo.org/5/exceptions/#what-if-i-don-t-want-that) 以防万一 我想使用装饰器样式。上面的链接文档仅显示使用单击(手动)创建命令时的用法。 有可能吗?下面显示了一个最小的示例。它说明了在从 gatherarguments

returning 之后 click 如何直接调用 sys.exit()
import click

@click.command()
@click.option('--name', help='Enter Name')
@click.pass_context
def gatherarguments(ctx, name):
    return ctx

def usectx(ctx):
    print("Name is %s" % ctx.params.name)

if __name__ == '__main__':
    ctx = gatherarguments()
    print(ctx) # is never called
    usectx(ctx) # is never called 

$ python test.py --name Your_Name

我希望它是无状态的,也就是说,没有任何 click.group 功能 - 我只想要结果,而我的应用程序不退出。

仅发送 standalone_mode 作为关键字参数对我有用:

from __future__ import print_function
import click

@click.command()
@click.option('--name', help='Enter Name')
@click.pass_context
def gatherarguments(ctx, name):
    return ctx

def usectx(ctx):
    print("Name is %s" % ctx.params['name'])

if __name__ == '__main__':
    ctx = gatherarguments(standalone_mode=False)
    print(ctx)
    usectx(ctx)

输出:

./clickme.py --name something
<click.core.Context object at 0x7fb671a51690>
Name is something