Python单击多个命令名称 [英] Python Click multiple command names
问题描述
是否可以使用Python Click做类似的事情?
Is it possible to do something like this with Python Click?
@click.command(name=['my-command', 'my-cmd'])
def my_command():
pass
我希望我的命令行类似于:
I want my command lines to be something like:
mycli my-command
和
mycli my-cmd
但引用相同的函数。
我需要做一个 AliasedGroup 之类的课程吗?
Do I need to do a class like AliasedGroup?
推荐答案
AliasedGroup 不是您想要的,因为它允许最短的前缀匹配,并且看来您需要实际的别名。但是该示例确实提供了可行方向的提示。它继承自 click.Group
并覆盖某些行为。
AliasedGroup is not what you are after, since it allows a shortest prefix match, and it appears you need actual aliases. But that example does provide hints in a direction that can work. It inherits from click.Group
and overides some behavior.
这里是一种处理所追求的目标的方法:
Here is a one way to approach what you are after:
该类覆盖了 click.Group.command()
方法,用于装饰命令功能。它增加了传递命令别名列表的功能。该类还添加了一个引用别名命令的简短帮助。
This class overides the click.Group.command()
method which is used to decorate command functions. It adds the ability to pass a list of command aliases. This class also adds a short help which references the aliased command.
class CustomMultiCommand(click.Group):
def command(self, *args, **kwargs):
"""Behaves the same as `click.Group.command()` except if passed
a list of names, all after the first will be aliases for the first.
"""
def decorator(f):
if isinstance(args[0], list):
_args = [args[0][0]] + list(args[1:])
for alias in args[0][1:]:
cmd = super(CustomMultiCommand, self).command(
alias, *args[1:], **kwargs)(f)
cmd.short_help = "Alias for '{}'".format(_args[0])
else:
_args = args
cmd = super(CustomMultiCommand, self).command(
*_args, **kwargs)(f)
return cmd
return decorator
使用自定义类
通过传递 cls
参数到 click.group()
装饰器,通过 group.command()
添加到组的任何命令都可以会被传递命令名称列表。
Using the Custom Class
By passing the cls
parameter to the click.group()
decorator, any commands added to the group via the the group.command()
can be passed a list of command names.
@click.group(cls=CustomMultiCommand)
def cli():
"""My Excellent CLI"""
@cli.command(['my-command', 'my-cmd'])
def my_command():
....
测试代码:
Test Code:
import click
@click.group(cls=CustomMultiCommand)
def cli():
"""My Excellent CLI"""
@cli.command(['my-command', 'my-cmd'])
def my_command():
"""This is my command"""
print('Running the command')
if __name__ == '__main__':
cli('--help'.split())
测试结果:
Test Results:
Usage: my_cli [OPTIONS] COMMAND [ARGS]...
My Excellent CLI
Options:
--help Show this message and exit.
Commands:
my-cmd Alias for 'my-command'
my-command This is my command
这篇关于Python单击多个命令名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!