gpt4 book ai didi

Python点击组: How to have -h/--help for all commands

转载 作者:行者123 更新时间:2023-12-01 06:34:41 24 4
gpt4 key购买 nike

上下文:

我有几个带有大量子命令的脚本,我想使用click将其转换为

目前,所有这些命令都接受 -h--help 以显示帮助选项。我想保持这种行为。

问题:

click 默认接受 --help 显示帮助文本,但不接受 -h

对于点击命令,可以通过添加轻松更改。

@click.group()
@click.help_option("--help", "-h")
def cli():
""" the doc string """
enter code here

@cli.command()
@click.help_option("--help", "-h")
def mycommand()
pass

@cli.command()
@click.help_option("--help", "-h")
def mycommand1()
pass

...

但是,如果我有数十个命令,我必须重新应用装饰器行

@click.help_option("--help", "-h")

每个子命令。

有什么技巧可以避免在任何地方都写这一行吗?

最佳答案

您需要定义 CONTEXT_SETTINGS 并按如下方式使用它:

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS)
def cli():
pass

来自点击documentation :

Help Parameter Customization Changelog The help parameter is implemented in Click in a very special manner. Unlike regular parameters it’s automatically added by Click for any command and it performs automatic conflict resolution. By default it’s called --help, but this can be changed. If a command itself implements a parameter with the same name, the default help parameter stops accepting it. There is a context setting that can be used to override the names of the help parameters called help_option_names.

This example changes the default parameters to -h and --help instead of just --help:

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS) def cli(): pass And what it looks like:

$ cli -h Usage: cli [OPTIONS]

Options: -h, --help Show this message and exit.

关于Python点击组: How to have -h/--help for all commands,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59733806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com