snippetpythonclickModeratepending
Python click -- modern CLI application framework
Viewed 0 times
clickCLIsubcommandoptionargumentgroup
pythonterminal
Problem
argparse is verbose and hard to compose for complex CLIs with subcommands, options, and argument validation.
Solution
Use click for declarative CLI building with decorators. Supports subcommands, automatic help, type validation, and colored output.
Code Snippets
Click CLI with subcommands and options
import click
@click.group()
@click.version_option('1.0.0')
def cli():
"""My awesome tool."""
pass
@cli.command()
@click.argument('name')
@click.option('--greeting', '-g', default='Hello', help='Greeting to use')
@click.option('--count', '-n', default=1, type=int, help='Repeat count')
@click.option('--loud', is_flag=True, help='Uppercase output')
def hello(name, greeting, count, loud):
"""Greet someone."""
msg = f'{greeting}, {name}!'
if loud:
msg = msg.upper()
for _ in range(count):
click.echo(click.style(msg, fg='green'))
@cli.command()
@click.argument('src', type=click.Path(exists=True))
@click.argument('dst', type=click.Path())
@click.confirmation_option(prompt='Are you sure?')
def copy(src, dst):
"""Copy SRC to DST."""
click.echo(f'Copying {src} -> {dst}')
if __name__ == '__main__':
cli()Revisions (0)
No revisions yet.