从代码中调用点击命令

Chr*_*lly 8 python command-line-interface python-click

我有一个函数,使用click打包为命令。所以看起来像这样:

@click.command()
@click.option('-w', '--width', type=int, help="Some helping message", default=0)
[... some other options ...]
def app(width, [... some other option arguments...]):
    [... function code...]
Run Code Online (Sandbox Code Playgroud)

我对此功能有不同的用例。有时,可以通过命令行调用它,但是有时候我也想直接调用该函数

from file_name import app
width = 45
app(45, [... other arguments ...]) 
Run Code Online (Sandbox Code Playgroud)

我们该怎么做?我们如何使用click调用已包装为命令的函数?我找到了这篇相关的文章,但是我不清楚如何使它适应我的情况(即,从头开始构建Context类并在click命令功能之外使用它)。

编辑:我应该提到:我不能(轻松)修改包含要调用的函数的程序包。因此,我正在寻找的解决方案是如何从呼叫方进行处理。

Mas*_*son 17

我尝试使用 Python 3.7 并单击 7 以下代码:

import click

@click.command()
@click.option('-w', '--width', type=int, default=0)
@click.option('--option2')
@click.argument('argument')
def app(width, option2, argument):
    click.echo("params: {} {} {}".format(width, option2, argument))
    assert width == 3
    assert option2 == '4'
    assert argument == 'arg'


app(["arg", "--option2", "4", "-w", 3], standalone_mode=False)

app(["arg", "-w", 3, "--option2", "4" ], standalone_mode=False)

app(["-w", 3, "--option2", "4", "arg"], standalone_mode=False)

Run Code Online (Sandbox Code Playgroud)

所有app通话均正常!

  • @jaromrax你的意思是在第一个应用程序调用后程序退出?我遇到了这个问题,并通过用 try except 语句包围每个应用程序调用来修复它。特别是 SystemExit 除外 (3认同)

Pie*_*ico 12

文档中描述了此用例。

有时,从一个命令调用另一个命令可能会很有趣。Click 通常不鼓励这种模式,但尽管如此,这种模式还是有可能的。为此,您可以使用 Context.invoke() 或 Context.forward() 方法。

cli = click.Group()

@cli.command()
@click.option('--count', default=1)
def test(count):
    click.echo('Count: %d' % count)

@cli.command()
@click.option('--count', default=1)
@click.pass_context
def dist(ctx, count):
    ctx.forward(test)
    ctx.invoke(test, count=42)
Run Code Online (Sandbox Code Playgroud)

它们的工作方式类似,但不同之处在于 Context.invoke() 仅使用您作为调用者提供的参数调用另一个命令,而 Context.forward() 则填充当前命令中的参数。


Mik*_*maa 9

如果只想调用底层函数,可以直接以click.Command.callback. Click 将底层包装的 Python 函数存储为类成员。请注意,直接调用该函数将绕过所有单击验证,并且不会出现任何单击上下文信息。

下面是一个示例代码,它迭代click.Command当前 Python 模块中的所有对象,并从中创建可调用函数的字典。

from functools import partial
from inspect import getmembers

import click


all_functions_of_click_commands = {}

def _call_click_command(cmd: click.Command, *args, **kwargs):
    result = cmd.callback(*args, **kwargs)
    return result

# Pull out all Click commands from the current module
module = sys.modules[__name__]
for name, obj in getmembers(module):
    if isinstance(obj, click.Command) and not isinstance(obj, click.Group):
        # Create a wrapper Python function that calls click Command.
        # Click uses dash in command names and dash is not valid Python syntax
        name = name.replace("-", "_") 
        # We also set docstring of this function correctly.
        func = partial(_call_click_command, obj)
        func.__doc__ = obj.__doc__
        all_functions_of_click_commands[name] = func
Run Code Online (Sandbox Code Playgroud)

完整的示例可以在binance-api-test-tool源代码中找到。


Ste*_*uch 5

您可以click通过从参数重构命令行来从常规代码中调用命令功能。使用您的示例,它看起来可能像这样:

call_click_command(app, width, [... other arguments ...])
Run Code Online (Sandbox Code Playgroud)

码:

def call_click_command(cmd, *args, **kwargs):
    """ Wrapper to call a click command

    :param cmd: click cli command function to call 
    :param args: arguments to pass to the function 
    :param kwargs: keywrod arguments to pass to the function 
    :return: None 
    """

    # Get positional arguments from args
    arg_values = {c.name: a for a, c in zip(args, cmd.params)}
    args_needed = {c.name: c for c in cmd.params
                   if c.name not in arg_values}

    # build and check opts list from kwargs
    opts = {a.name: a for a in cmd.params if isinstance(a, click.Option)}
    for name in kwargs:
        if name in opts:
            arg_values[name] = kwargs[name]
        else:
            if name in args_needed:
                arg_values[name] = kwargs[name]
                del args_needed[name]
            else:
                raise click.BadParameter(
                    "Unknown keyword argument '{}'".format(name))


    # check positional arguments list
    for arg in (a for a in cmd.params if isinstance(a, click.Argument)):
        if arg.name not in arg_values:
            raise click.BadParameter("Missing required positional"
                                     "parameter '{}'".format(arg.name))

    # build parameter lists
    opts_list = sum(
        [[o.opts[0], str(arg_values[n])] for n, o in opts.items()], [])
    args_list = [str(v) for n, v in arg_values.items() if n not in opts]

    # call the command
    cmd(opts_list + args_list)
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?

之所以可行,是因为click是一个设计良好的OO框架。@click.Command可以对对象进行自省以确定其期望的参数。然后可以构造一个命令行,该命令行看起来像单击所期望的命令行。

测试代码:

import click

@click.command()
@click.option('-w', '--width', type=int, default=0)
@click.option('--option2')
@click.argument('argument')
def app(width, option2, argument):
    click.echo("params: {} {} {}".format(width, option2, argument))
    assert width == 3
    assert option2 == '4'
    assert argument == 'arg'


width = 3
option2 = 4
argument = 'arg'

if __name__ == "__main__":
    commands = (
        (width, option2, argument, {}),
        (width, option2, dict(argument=argument)),
        (width, dict(option2=option2, argument=argument)),
        (dict(width=width, option2=option2, argument=argument),),
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> {}'.format(cmd))
            time.sleep(0.1)
            call_click_command(app, *cmd[:-1], **cmd[-1])

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise
Run Code Online (Sandbox Code Playgroud)

检测结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> (3, 4, 'arg', {})
params: 3 4 arg
-----------
> (3, 4, {'argument': 'arg'})
params: 3 4 arg
-----------
> (3, {'option2': 4, 'argument': 'arg'})
params: 3 4 arg
-----------
> ({'width': 3, 'option2': 4, 'argument': 'arg'},)
params: 3 4 arg
Run Code Online (Sandbox Code Playgroud)

  • **Click 从根本上来说是疯狂的。** 调用简单 Click 修饰函数的*唯一*方法是定义一个不平凡的 50 行 `sys.argv` 工厂函数,在 `O(n**2)` 中运行动态(且昂贵)将 Python 参数列表反编译为 POSIX 兼容参数列表的位置参数数量的时间?这确实很糟糕——但我毫不怀疑这就是 Click 的要求。Click 开发者:*您的核心前提需要重新思考。* (7认同)