python - 如何检测 '--help' 何时被调用?

标签 python command-line-interface python-click

我的 Click 7.0 应用程序有一个组,有多个命令,由主 cli 调用。功能如下:

import click

@click.group()
@click.pass_context
def cli(ctx):
   "This is cli helptext"

    click.echo('cli called')
    click.echo('cli args: {0}'.format(ctx.args))

@cli.group(chain=True)
@click.option('-r', '--repeat', default=1, type=click.INT, help='repeat helptext')
@click.pass_context
def chainedgroup(ctx, repeat):
    "This is chainedgroup helptext"

    for _ in range(repeat):
        click.echo('chainedgroup called')
    click.echo('chainedgroup args: {0}'.format(ctx.args))

@chainedgroup.command()
@click.pass_context
def command1(ctx):
    "This is command1 helptext"

    print('command1 called')
    print('command1 args: {0}'.format(ctx.args))

@chainedgroup.command()
@click.pass_context
def command2(ctx):
    "This is command2 helptext"

    print('command2 called')
    print('command2 args: {0}'.format(ctx.args))

运行:

$ testcli --help
$ testcli chainedgroup --help
$ testcli chainedgroup command1 --help

帮助文本按预期显示 - 只不过父函数在进程中无意中运行。单个条件检查是否 '--help'包含在ctx.args中应该足以解决这个问题,但是有谁知道如何/何时'--help'通过了吗?因为有了这段代码,ctx.args每次都是空的。

最佳答案

如果 argparse 不是一个选项,那么:

if '--help' in sys.argv:
...

关于python - 如何检测 '--help' 何时被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56420331/

相关文章:

vue.js - 如何为 Vue 项目指定有效的入口点/文件?

c++ - 使用 numericupdown 控制图像的亮度

python - 禁止在python点击中传递几个特性开关

python - 如何访问继承类的关键字参数默认值

python - 如何使用 "chain"迭代器?

linux - 在 Ubuntu Server (Linux) 中使用 rm 时如何更改错误消息

python click 应用程序失败并显示 "missing argument"但无法找到问题

python - 如何更有效地将字符串中的多个字符映射为单个字符?

python - Django 播客迁移 : TypeError: __init__() missing 1 required positional argument: 'on_delete'