我试图了解有关Click的一些实施细节。我有以下示例代码:
#cli.py
import click
@click.group()
def cli():
pass
@cli.group()
def show():
""" Define the environment of the product """
pass
@show.command()
def name():
click.echo("run show name command")
@show.command()
def height():
click.echo("run show height command")
if __name__ == "__main__":
cli()
使用此代码,name
和height
是show
组的子 命令 。但是,从语义上讲,这实际上没有任何意义。它们更像是“显示”命令的 参数 。
我知道我可以拥有一个带有“属性”参数的命令,通过该命令,我可以基于“属性”的字符串值调用其他函数。但是,我认为一旦存在“属性”的几种可能性,维护起来就很麻烦。
如果可以编辑帮助消息,我相信我仍然可以使用上面的结构。运行cli.py show --help
时,会获得命令组的默认帮助消息:
Usage: cli.py show [OPTIONS] COMMAND [ARGS]...
Define the environment of the product
Options:
--help Show this message and exit.
Commands:
height
name
是否可以编辑帮助消息,以将“命令”更改为“参数”?我知道如何在click.group()装饰器中更改用法声明,但不确定如何修改帮助消息本身。
我想获得的帮助信息如下:
Usage: cli.py show [OPTIONS] ARG
Define the environment of the product
Options:
--help Show this message and exit.
Arguments:
height
name
这样可能吗?
我正在使用python3和Click 6.7
答案 0 :(得分:0)
您可以通过使用组的自定义类来更改子命令help给出的消息。可以通过从click.Group
继承并更改format_commands()
方法来制成自定义类,例如:
class HelpAsArgs(click.Group):
# change the section head of sub commands to "Arguments"
def format_commands(self, ctx, formatter):
rows = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
if cmd is None:
continue
help = cmd.short_help or ''
rows.append((subcommand, help))
if rows:
with formatter.section('Arguments'):
formatter.write_dl(rows)
import click
@click.group()
def cli():
pass
@cli.group(cls=HelpAsArgs)
def show():
""" Define the environment of the product """
pass
@show.command()
def name():
click.echo("run show name command")
@show.command()
def height():
click.echo("run show height command")
if __name__ == "__main__":
commands = (
'show',
'show --help',
'--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)
cli(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)]
-----------
> show
Usage: test.py show [OPTIONS] COMMAND [ARGS]...
Define the environment of the product
Options:
--help Show this message and exit.
Arguments:
height
name
-----------
> show --help
Usage: test.py show [OPTIONS] COMMAND [ARGS]...
Define the environment of the product
Options:
--help Show this message and exit.
Arguments:
height
name
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
show Define the environment of the product