gpt4 book ai didi

python - 单击带有可选参数的工具

转载 作者:行者123 更新时间:2023-12-04 08:15:39 24 4
gpt4 key购买 nike

我想编写一个以 FILENAME 作为参数的 CLI hello,除非给出了选项 -s STRING,在这种情况下直接处理 STRING。程序应该打印 hello {NAME}其中 name 要么通过 STRING 给出,要么被视为文件 FILENAME 的内容。
例子:

$ cat myname.txt
john

$ hello myname.txt
hello john

$ hello -s paul
hello paul
一种可能的解决方法是使用两个选项:
@click.command()
@click.option("-f", "--filename", type=str)
@click.option("-s", "--string", type=str)
def main(filename: str, string: str):
if filename:
...
if string:
....
但这意味着我必须调用 hello有一面旗帜。

最佳答案

您可以使用点击 argument并使其不需要,例如:

import click
@click.command()
@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}')

关于python - 单击带有可选参数的工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65719432/

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