gpt4 book ai didi

python - 如果不正确或点击任务选项显示帮助

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:58 25 4
gpt4 key购买 nike

当我将无效参数放入命令时,只显示:

Usage: ugen.py [OPTIONS]

Error: Missing option "-o" / "--out_file".

我想用--help选项显示整个帮助信息

我的修饰函数:

@click.command(name="ugen")
@click.help_option("-h", "--help")
@click.option(
"-o", "--out_file",
help="Output file where data is written.",
required=True
)
@click.option(
"-i", "--in_file", multiple=True,
help=(
"Input file/s from which data is read. "
"Can be provided multiple times. "
"Although always with specifier -i/--in_file."
),
required=True
)
def main(out_file, in_file):
code here

最佳答案

您可以 Hook 命令调用,然后根据需要显示帮助,如:

自定义命令类

import click

class ShowUsageOnMissingError(click.Command):
def __call__(self, *args, **kwargs):
try:
return super(ShowUsageOnMissingError, self).__call__(
*args, standalone_mode=False, **kwargs)
except click.MissingParameter as exc:
exc.ctx = None
exc.show(file=sys.stdout)
click.echo()
try:
super(ShowUsageOnMissingError, self).__call__(['--help'])
except SystemExit:
sys.exit(exc.exit_code)

使用自定义类

要使用自定义类,只需将类传递给 click.command() 装饰器,例如:

@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
...

这是如何运作的?

之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.command() 装饰器通常实例化一个 click.Command 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Command 并覆盖所需的方法是一件相对容易的事情。

在这种情况下,我们覆盖 __call__() 并在打印异常后打印帮助。

测试代码

@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
click.echo(o)


if __name__ == "__main__":
commands = (
'-o outfile',
'',
'--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(), obj={})

except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise

结果

Click Version: 6.7
Python Version: 3.6.2 (default, Jul 17 2017, 23:14:31)
[GCC 5.4.0 20160609]
-----------
> -o outfile
outfile
-----------
>
Error: Missing option "-o".

Usage: test.py [OPTIONS]

Options:
-o TEXT Output file where data is written. [required]
--help Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS]

Options:
-o TEXT Output file where data is written. [required]
--help Show this message and exit.

关于python - 如果不正确或点击任务选项显示帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975203/

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