单击带有可选参数的工具

编程入门 行业动态 更新时间:2024-10-27 20:35:25
本文介绍了单击带有可选参数的工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想编写一个以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}')

更多推荐

单击带有可选参数的工具

本文发布于:2023-10-05 09:01:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   单击   参数   工具

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!