本文介绍了单击带有可选参数的工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个以FILENAME作为参数的CLI hello ,除非指定了-s STRING选项,否则将直接处理STRING.该程序应打印 hello {NAME} ,其中名称是通过STRING给出的,或者被视为文件FILENAME的内容.
I want to write a CLI hello that takes a FILENAME as an argument except when the option -s STRING is given, in which case the STRING is processed directly. The program should print hello {NAME} where name is either given via the STRING or taken to be the contents of the file FILENAME.
示例:
$ cat myname.txt john $ hello myname.txt hello john $ hello -s paul hello paul可能的解决方法是使用两个选项:
A possible workaround is to use two options:
@clickmand() @click.option("-f", "--filename", type=str) @click.option("-s", "--string", type=str) def main(filename: str, string: str): if filename: ... if string: ....但这意味着我必须用一个标志调用 hello .
but that means that I must call hello with a flag.
推荐答案您可以使用Click 参数,并使其不需要,例如:
You can use a Click argument and make it not required like:
import click @clickmand() @click.argument('filename', required=False) @click.option("-s", "--string") def main(filename, string): if None not in (filename, string): raise click.ClickException('filename argument and option string are mutually exclusive!') click.echo(f'Filename: {filename}') click.echo(f'String: {string}')更多推荐
单击带有可选参数的工具
发布评论