I'm having a conundrum with the Python Click library when parsing some CLI options.
I would like an option to act as a flag by itself, but optionally accept string values. E.g.:
$ myscript
⇒ option = False$ myscript -o
⇒ option = True$ myscript -o foobar
⇒ option = Foobar
Additionally, I would like the option to be "eager" (e.g. in "Click" terms abort execution after a callback), but this can be ignored for now.
When I define my arguments like this:
@click.command()
@click...
@click.option("-o", "option", is_flag=True, default=False)
def myscript(..., option):
I achieve example 1 and 2, but 3 is naturally impossible because the flag detects present/not present only.
When I define my arguments like this:
@click.command()
@click...
@click.option("-o", "--option", default="") # Let's assume I will cast empty string to False
def myscript(..., option):
I achieve 1 and 3, but 2 will fail with an Error: -c option requires an argument
.
This does not seems like an out-of-this world scenario, but I can't seem to be able to achieve this or find examples that behave like this.
How can I define an @click.option
that gets parsed like:
False
when not setTrue
when set but without valuestr
when set with value
argparse
on the other hand would support your requirements vianargs='*'
:parser.add_argument('-o', nargs='*')
. – Kirk