python - 更改 Click 的默认帮助选项的方法?

标签 python command-line-interface python-click

每当您使用 Click 创建命令或组时,都会有一个默认的 --help 选项来提供使用指南:

import click

@click.command()
def main():
    click.echo('Success!')

if __name__ == '__main__':
    main()

如果我使用 --help 运行该文件,我应该得到:

$ python file.py --help
Usage: file.py [OPTIONS]

Options:
--help  Show this message and exit.

现在,Click 允许您通过装饰器中的参数覆盖通过终端调用 help 选项的方式:

@click.command(
    context_settings=dict(
        help_option_names=['-f', '--foo']
    )
)
def main():
    click.echo('Success!')
$ python file.py -f
Usage: file.py [OPTIONS]

Options:
-f, --foo  Show this message and exit.

但是,翻遍Click的documentation ,我没有看到类似的选项来覆盖默认帮助消息


是否有指定给 click.command 的参数,以在终端中寻求帮助时覆盖文本“显示此消息并退出”

最佳答案

您可以使用help_option更改click的默认帮助选项装饰器

示例代码:

@click.command(add_help_option=False)
@click.help_option('--foo', '-f', help='Show my better message and exit')
def main():
    """The docstring is the Help Message"""
    click.echo('Success!')

测试代码:

if __name__ == "__main__":
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    print('-----------')
    cmd = 'main --foo'
    print('> ' + cmd)
    main(cmd.split())

测试结果:

Click Version: 8.1.3
Python Version: 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)]
-----------
> main --foo
Usage: test_code.py [OPTIONS]

  The docstring is the Help Message

Options:
  -f, --foo  Show my better message and exit

关于python - 更改 Click 的默认帮助选项的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72580254/

相关文章:

amazon-web-services - aws ec2 描述实例 : how to filter *out* spot instances?

linux - Hive 的 CLI 使用哪个 hive-site.xml

python - python 中不区分大小写的选择

python - Numpy随机选择分布误差

python - 将 map() 函数(来自 Pool 类)返回的列表转换为 Python 中的字典

python - CSV 到 Python 中的列表

javascript - 在 Linux CLI 中解释和执行任意 Javascript

python click 设置选项的允许值

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

python - `[row_index, [elements]]` 的嵌套列表到 Pandas 数据框?