Python 如何检测何时'--帮助';有人打过电话吗?
我的Click 7.0应用程序有一个组,有多个命令,由主Python 如何检测何时'--帮助';有人打过电话吗?,python,command-line-interface,python-click,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('-
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))
运行:
帮助文本按预期显示——除了父函数在进程中意外运行之外。一次条件检查以查看
'--help'
是否包含在ctx.args
中应该足以解决此问题,但是有人知道如何/何时传递'--help'
?因为有了这段代码,ctx.args
每次都是空的。为什么不使用argparse?它具有出色的CLI解析功能。如果argparse不是一个选项,那么:
if '--help' in sys.argv:
...
它是预构建的-单击看起来像argparse的装饰器(常识万岁) 这样你就可以写作了
python cl.py --name bob
看看
你好,鲍勃
帮助已经完成(因为它是argparse)
我一直很忙,只是有时间读懂这个
很抱歉延迟
单击
将传递给命令的参数存储在列表中。方法get\u os\u args()
返回这样的列表。您可以检查该列表中是否有--help
,以确定是否调用了help
标志。如下所示:
如果在click.get_os_args()中出现“--help”:
通过
我还应该注意,我打算对传递的命令反复使用repeat
循环,但我可以问一个单独的问题。在这个阶段切换到argparse
将意味着耗时的重新写入。重新发明轮子同样耗时。但这是你的时间,不是我的时间。如果你知道一种使用argparse
模仿这个的方法,我真的很高兴看到一个片段!老实说,我对argparse不太了解,学习python click已经足够快了。修复我的应用程序不再意味着耗时的重写。通过sys.argv
手动禁用和处理帮助解决了我的问题!
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
python cl.py --name bob
python cl.py --help
Usage: cl.py [OPTIONS]
Simple program that greets NAME for a total of COUNT times.
Options:
--count INTEGER Number of greetings.
--name TEXT The person to greet.
--help Show this message and exit.