Click tools with optional arguments

瘦欲@ 提交于 2021-02-16 20:22:46

问题


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.

example:

$ cat myname.txt
john

$ hello myname.txt
hello john

$ hello -s paul
hello paul

A possible workaround is to use two options:

@click.command()
@click.option("-f", "--filename", type=str)
@click.option("-s", "--string", type=str)
def main(filename: str, string: str):
    if filename:
        ...
    if string:
        ....

but that means that I must call hello with a flag.


回答1:


You can use a Click argument and make it not required like:

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}')


来源:https://stackoverflow.com/questions/65719432/click-tools-with-optional-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!