completion.py
This file
Path
examples/completion/completion.py
53 lines · 1.3 KiB · Python
Last changed by
Merge pull request #1622 from MLH-Fellowship/1484-redesign-completionDavid Lordbefore adoption6c8301e
History of this fileTake it
1import os23import click4from click.shell_completion import CompletionItem567@click.group()8def cli():9 pass101112@cli.command()13@click.option("--dir", type=click.Path(file_okay=False))14def ls(dir):15 click.echo("\n".join(os.listdir(dir)))161718def get_env_vars(ctx, param, incomplete):19 # Returning a list of values is a shortcut to returning a list of20 # CompletionItem(value).21 return [k for k in os.environ if incomplete in k]222324@cli.command(help="A command to print environment variables")25@click.argument("envvar", shell_complete=get_env_vars)26def show_env(envvar):27 click.echo(f"Environment variable: {envvar}")28 click.echo(f"Value: {os.environ[envvar]}")293031@cli.group(help="A group that holds a subcommand")32def group():33 pass343536def list_users(ctx, param, incomplete):37 # You can generate completions with help strings by returning a list38 # of CompletionItem. You can match on whatever you want, including39 # the help.40 items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]4142 for value, help in items:43 if incomplete in value or incomplete in help:44 yield CompletionItem(value, help=help)454647@group.command(help="Choose a user")48@click.argument("user", shell_complete=list_users)49def select_user(user):50 click.echo(f"Chosen user is {user}")515253cli.add_command(group)