如何使用 2 个或更多参数创建自定义 Flask CLI 命令?

How to create custom Flask CLI commands with 2 or more arguments?

我想制作自定义 Flask CLI 命令。当我只使用 1 个参数时它工作正常但它不适用于 2 个或更多参数。我正在使用下面的代码,但它因 2 个或更多参数而失败:

# Usage: flask power 2 3 
# Output: 6
@app.cli.command()
@click.argument('x','y')
def power(x, y):
  print(int(x)**int(y))

以下代码只需 1 个参数即可正常工作

# Usage: flask power 2
# Output: 6
@app.cli.command()
@click.argument('x')
def power(x):
  print(int(x)**3)

使用 2 个或更多参数代码重现的错误是:

flask power 2 3
Traceback (most recent call last):
  File "/home/user/.local/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/home/user/.local/lib/python3.5/site-packages/flask/cli.py", line 894, in main
    cli.main(args=args, prog_name=name)
  File "/home/user/.local/lib/python3.5/site-packages/flask/cli.py", line 557, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 1254, in invoke
    cmd_name, cmd, args = self.resolve_command(ctx, args)
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 1297, in resolve_command
    cmd = self.get_command(ctx, cmd_name)
  File "/home/user/.local/lib/python3.5/site-packages/flask/cli.py", line 515, in get_command
    rv = info.load_app().cli.get_command(ctx, name)
  File "/home/user/.local/lib/python3.5/site-packages/flask/cli.py", line 372, in load_app
    app = locate_app(self, import_name, name)
  File "/home/user/.local/lib/python3.5/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "/projects/challenge/myflaskproj/__init__.py", line 6, in <module>
    from myflaskproj.commands import power, repeat
  File "/projects/challenge/myflaskproj/commands.py", line 6, in <module>
    @click.argument('x','y')
  File "/home/user/.local/lib/python3.5/site-packages/click/decorators.py", line 168, in decorator
    _param_memo(f, ArgumentClass(param_decls, **attrs))
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 1984, in __init__
    Parameter.__init__(self, param_decls, required=required, **attrs)
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 1483, in __init__
    param_decls or (), expose_value
  File "/home/user/.local/lib/python3.5/site-packages/click/core.py", line 2019, in _parse_decls
    " {}".format(len(decls))
TypeError: Arguments take exactly one parameter declaration, got 2

如何让命令在此方法中接受 2 个参数?我在某处做错了吗?非常感谢您的帮助。

我看到了一些使用 BluePrint 的解决方案,但我不想使用 Blueprint 来完成我的工作 运行!以上代码简单易用。 我不知道我哪里做错了什么!!非常感谢额外的帮助!!

@click.arguments这种方式不接受多个参数。

改为使用

@app.cli.command()
@click.argument('x', nargs=1)
@click.argument('y', nargs=1)
def power(x, y):
    print(int(x)**int(y))

参考文档here