一个没有名字的命令,在 Click
A command without name, in Click
我想要一个命令行工具,用法如下:
$ program <arg> does something, no command name required
$ program cut <arg>
$ program eat <arg>
Click 代码如下所示:
@click.group()
def main() :
pass
@main.command()
@click.argument('arg')
def noname(arg) :
# does stuff
@main.command()
@click.argument('arg')
def cut(arg) :
# cuts stuff
@main.command()
@click.argument('arg')
def eat(arg) :
# eats stuff
我的问题是,使用这段代码,总是需要一个命令名称,即:我需要 运行 $ program noname arg
。但是我希望能够运行$ program arg
。
有一个选项供您选择,“无命令的组调用
":
@click.group(invoke_without_command=True)
@click.pass_context
def main(ctx):
if not ctx.invoked_subcommand:
print('main stuff')
由于 default 命令引入的歧义,您的方案存在一些挑战。无论如何,这是可以通过 click
实现的一种方法。如测试结果所示,生成的帮助不太理想,但可能还不错。
自定义 Class:
import click
class DefaultCommandGroup(click.Group):
"""allow a default command for a group"""
def command(self, *args, **kwargs):
default_command = kwargs.pop('default_command', False)
if default_command and not args:
kwargs['name'] = kwargs.get('name', '<>')
decorator = super(
DefaultCommandGroup, self).command(*args, **kwargs)
if default_command:
def new_decorator(f):
cmd = decorator(f)
self.default_command = cmd.name
return cmd
return new_decorator
return decorator
def resolve_command(self, ctx, args):
try:
# test if the command parses
return super(
DefaultCommandGroup, self).resolve_command(ctx, args)
except click.UsageError:
# command did not parse, assume it is the default command
args.insert(0, self.default_command)
return super(
DefaultCommandGroup, self).resolve_command(ctx, args)
使用自定义 Class
要使用自定义 class,请将 cls
参数传递给 click.group()
装饰器。然后为默认命令传递 default_command=True
。
@click.group(cls=DefaultCommandGroup)
def a_group():
"""My Amazing Group"""
@a_group.command(default_command=True)
def a_command():
"""a command under the group"""
这是如何工作的?
之所以可行,是因为 click
是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们覆盖 click.Group.command()
,以便在添加命令时找到默认命令。此外,我们覆盖 click.Group.resolve_command()
以便在第一次解析不成功时插入默认命令名称。
测试代码:
@click.group(cls=DefaultCommandGroup)
def main():
pass
@main.command(default_command=True)
@click.argument('arg')
def noname(arg):
""" does stuff """
click.echo('default: {}'.format(arg))
@main.command()
@click.argument('arg')
def cut(arg):
""" cuts stuff """
click.echo('cut: {}'.format(arg))
@main.command()
@click.argument('arg')
def eat(arg):
""" eats stuff """
click.echo('eat: {}'.format(arg))
if __name__ == "__main__":
commands = (
'an_arg',
'cut cut_arg',
'eat eat_arg',
'--help',
'cut --help',
'eat --help',
'',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for command in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + command)
time.sleep(0.1)
main(command.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc,
(click.ClickException, SystemExit)):
raise
结果:
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)]
-----------
> an_arg
default: an_arg
-----------
> cut cut_arg
cut: cut_arg
-----------
> eat eat_arg
eat: eat_arg
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
<> does stuff
cut cuts stuff
eat eats stuff
-----------
> cut --help
Usage: test.py cut [OPTIONS] ARG
cuts stuff
Options:
--help Show this message and exit.
-----------
> eat --help
Usage: test.py eat [OPTIONS] ARG
eats stuff
Options:
--help Show this message and exit.
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
<> does stuff
cut cuts stuff
eat eats stuff
click-default-group 正在做您正在寻找的事情。它是点击贡献集合的一部分。
这样做而不是使用 invoke_without_command
的优点是它可以将选项和参数完美地传递给默认命令,这对于内置功能来说并非微不足道(甚至可能)。
示例代码:
import click
from click_default_group import DefaultGroup
@click.group(cls=DefaultGroup, default='foo', default_if_no_args=True)
def cli():
print("group execution")
@cli.command()
@click.option('--config', default=None)
def foo(config):
click.echo('foo execution')
if config:
click.echo(config)
然后,可以调用 foo
命令,其选项为:
$ program foo --config bar <-- normal way to call foo
$ program --config bar <-- foo is called and the option is forwarded.
Not possible with vanilla Click.
我想要一个命令行工具,用法如下:
$ program <arg> does something, no command name required
$ program cut <arg>
$ program eat <arg>
Click 代码如下所示:
@click.group()
def main() :
pass
@main.command()
@click.argument('arg')
def noname(arg) :
# does stuff
@main.command()
@click.argument('arg')
def cut(arg) :
# cuts stuff
@main.command()
@click.argument('arg')
def eat(arg) :
# eats stuff
我的问题是,使用这段代码,总是需要一个命令名称,即:我需要 运行 $ program noname arg
。但是我希望能够运行$ program arg
。
有一个选项供您选择,“无命令的组调用 ":
@click.group(invoke_without_command=True)
@click.pass_context
def main(ctx):
if not ctx.invoked_subcommand:
print('main stuff')
由于 default 命令引入的歧义,您的方案存在一些挑战。无论如何,这是可以通过 click
实现的一种方法。如测试结果所示,生成的帮助不太理想,但可能还不错。
自定义 Class:
import click
class DefaultCommandGroup(click.Group):
"""allow a default command for a group"""
def command(self, *args, **kwargs):
default_command = kwargs.pop('default_command', False)
if default_command and not args:
kwargs['name'] = kwargs.get('name', '<>')
decorator = super(
DefaultCommandGroup, self).command(*args, **kwargs)
if default_command:
def new_decorator(f):
cmd = decorator(f)
self.default_command = cmd.name
return cmd
return new_decorator
return decorator
def resolve_command(self, ctx, args):
try:
# test if the command parses
return super(
DefaultCommandGroup, self).resolve_command(ctx, args)
except click.UsageError:
# command did not parse, assume it is the default command
args.insert(0, self.default_command)
return super(
DefaultCommandGroup, self).resolve_command(ctx, args)
使用自定义 Class
要使用自定义 class,请将 cls
参数传递给 click.group()
装饰器。然后为默认命令传递 default_command=True
。
@click.group(cls=DefaultCommandGroup)
def a_group():
"""My Amazing Group"""
@a_group.command(default_command=True)
def a_command():
"""a command under the group"""
这是如何工作的?
之所以可行,是因为 click
是一个设计良好的 OO 框架。 @click.group()
装饰器通常实例化一个 click.Group
对象,但允许使用 cls
参数覆盖此行为。因此,在我们自己的 class 中继承 click.Group
并覆盖所需的方法是一件相对容易的事情。
在这种情况下,我们覆盖 click.Group.command()
,以便在添加命令时找到默认命令。此外,我们覆盖 click.Group.resolve_command()
以便在第一次解析不成功时插入默认命令名称。
测试代码:
@click.group(cls=DefaultCommandGroup)
def main():
pass
@main.command(default_command=True)
@click.argument('arg')
def noname(arg):
""" does stuff """
click.echo('default: {}'.format(arg))
@main.command()
@click.argument('arg')
def cut(arg):
""" cuts stuff """
click.echo('cut: {}'.format(arg))
@main.command()
@click.argument('arg')
def eat(arg):
""" eats stuff """
click.echo('eat: {}'.format(arg))
if __name__ == "__main__":
commands = (
'an_arg',
'cut cut_arg',
'eat eat_arg',
'--help',
'cut --help',
'eat --help',
'',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for command in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + command)
time.sleep(0.1)
main(command.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc,
(click.ClickException, SystemExit)):
raise
结果:
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)]
-----------
> an_arg
default: an_arg
-----------
> cut cut_arg
cut: cut_arg
-----------
> eat eat_arg
eat: eat_arg
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
<> does stuff
cut cuts stuff
eat eats stuff
-----------
> cut --help
Usage: test.py cut [OPTIONS] ARG
cuts stuff
Options:
--help Show this message and exit.
-----------
> eat --help
Usage: test.py eat [OPTIONS] ARG
eats stuff
Options:
--help Show this message and exit.
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
<> does stuff
cut cuts stuff
eat eats stuff
click-default-group 正在做您正在寻找的事情。它是点击贡献集合的一部分。
这样做而不是使用 invoke_without_command
的优点是它可以将选项和参数完美地传递给默认命令,这对于内置功能来说并非微不足道(甚至可能)。
示例代码:
import click
from click_default_group import DefaultGroup
@click.group(cls=DefaultGroup, default='foo', default_if_no_args=True)
def cli():
print("group execution")
@cli.command()
@click.option('--config', default=None)
def foo(config):
click.echo('foo execution')
if config:
click.echo(config)
然后,可以调用 foo
命令,其选项为:
$ program foo --config bar <-- normal way to call foo
$ program --config bar <-- foo is called and the option is forwarded.
Not possible with vanilla Click.