bashcompletion.py
This file
Path
examples/bashcompletion/bashcompletion.py
45 lines · 1.2 KiB · Python
Last changed by
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
History of this fileTake it
1import os23import click456@click.group()7def cli():8 pass91011def get_env_vars(ctx, args, incomplete):12 # Completions returned as strings do not have a description displayed.13 for key in os.environ.keys():14 if incomplete in key:15 yield key161718@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo(f"Environment variable: {envvar}")22 click.echo(f"Value: {os.environ[envvar]}")232425@click.group(help="A group that holds a subcommand")26def group():27 pass282930def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).33 users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the35 # description string too!36 return [user for user in users if incomplete in user[0] or incomplete in user[1]]373839@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo(f"Chosen user is {user}")434445cli.add_command(group)