Python 如果单击中的任务选项不正确,则显示帮助
当我将无效参数放入命令时,只显示以下内容:Python 如果单击中的任务选项不正确,则显示帮助,python,python-3.x,python-click,Python,Python 3.x,Python Click,当我将无效参数放入命令时,只显示以下内容: 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
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
您可以挂接命令调用,然后根据需要显示帮助,如: 自定义命令类 使用自定义类 要使用自定义类,只需将该类传递给
click.command()
decorator,如:
@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
...
这是怎么回事?
这是因为click是一个设计良好的OO框架。@click.command()
decorator通常实例化click.command
对象,但允许使用cls
参数过度处理此行为。因此,在我们自己的类中继承click.Command
并超越所需的方法是一件相对容易的事情
在这种情况下,我们重写\uuuu call\uuu()
,并在打印异常后打印帮助
测试代码
后果
@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
...
@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.