python 点击​​命令的详细帮助

标签 python command-line-interface python-click

有没有办法获得点击命令的单独详细帮助?例如打印该命令的选项/参数。

此 cli 示例:

import click

@click.group()
def cli():
    pass

@cli.command()
@click.argument('arg1')
@click.option('--option1', default=1)
def cmd1(arg1):
    print(arg1)

if __name__ == '__main__':
    cli()

默认帮助仅提供以下内容:

> python cli.py --help

Usage: cli.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  cmd1

我想要这样的东西:

> python cli.py --help cmd1

...
Command cmd1
Arguments:
    arg1
Options:
    --option1
....

这可能吗?

最佳答案

如果您将 --help 放在命令后面,您将得到您想要的内容。

python cli.py cmd1 --help

测试代码:

import click

@click.group()
def cli():
    pass

@cli.command()
@click.argument('arg1')
@click.option('--option1', default=1)
def cmd1(arg1):
    print(arg1)


if __name__ == "__main__":
    commands = (
        'cmd1 --help',
        '--help',
        '',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.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)]
-----------
> cmd1 --help
Usage: test.py cmd1 [OPTIONS] ARG1

Options:
  --option1 INTEGER
  --help             Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  cmd1
-----------
> 
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  cmd1

关于python 点击​​命令的详细帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858816/

相关文章:

python - 用于无排名分类器(例如 OSVM)的 AUC-ROC

python - 如何对验证日期时间是否为特定 ISO 格式的函数进行单元测试?

c# - 如何通过 PID 向 CMD 进程发送关闭命令

python - 单击配置文件产生错误

python - python-click MultiCommand 的全局选项

python - 如何记录使用 Sphinx 的点击命令?

python - 为什么我不能让 Python 的 urlopen() 方法在 Windows 上运行?

python - 使用元组设置 Tkinter 条目

php - 如何减慢 DOS/windows 命令提示符的输出速度

python - 什么是 CLI 循环?和普通循环有什么区别?