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

标签 python python-click

上下文:

我有几个带有大量子命令的脚本,我想使用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/

相关文章:

python - 如何使用 Python 的 click (Command Line Interface Creation Kit) 包将变量传递给其他方法

python - 这段 Python 代码在做什么?

Python:如何将列中仅包含数字组件的字符串条目转换为整数?

Python numpy 参数排序

python - 我可以为对象提供单击命令,使用继承来消除重复代码吗?

python - 单击 : Use another function in chained commands with context object

python - python 括号不平衡

python - AppEngine 数据策略来处理每个用户的大索引?

Python - 单击命令行单元测试用例以获取来自命令行功能的输入提示

python - Python click 模块没有输出?