Skip to content Skip to sidebar Skip to footer

Click Tools With Optional Arguments

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

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

Post a Comment for "Click Tools With Optional Arguments"