2

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.

Stephen Rauch
50.1k32 gold badges119 silver badges143 bronze badges
asked Jan 14, 2021 at 12:59

1 Answer 1

4

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}')
answered Jan 16, 2021 at 1:02
Sign up to request clarification or add additional context in comments.

2 Comments

Quick question for clarification: you could use argument for both options in the given case, right?
@self Only now I figured out that I misunderstood your suggestion. I thought argument('some') would be a shortcut for option('-s', '--some',tyle=str): of course not both can be made an optional argument! Maybe the short introduction can be too short for people new to the Click API. ... the approach shown in the code leads to a good CLI.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.