python-click/examples/bashcompletion/bashcompletion.py

46 lines
1.2 KiB
Python
Raw Normal View History

2018-09-06 20:55:10 +02:00
import os
2020-07-21 08:23:42 +02:00
import click
2018-09-06 20:55:10 +02:00
@click.group()
def cli():
pass
def get_env_vars(ctx, args, incomplete):
2019-01-07 17:51:19 +01:00
# Completions returned as strings do not have a description displayed.
2018-09-06 20:55:10 +02:00
for key in os.environ.keys():
if incomplete in key:
yield key
2020-07-21 08:23:42 +02:00
@cli.command(help="A command to print environment variables")
2018-09-06 20:55:10 +02:00
@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)
def cmd1(envvar):
2020-07-21 08:23:42 +02:00
click.echo("Environment variable: {}".format(envvar))
click.echo("Value: {}".format(os.environ[envvar]))
2018-09-06 20:55:10 +02:00
2020-07-21 08:23:42 +02:00
@click.group(help="A group that holds a subcommand")
2018-09-06 20:55:10 +02:00
def group():
pass
def list_users(ctx, args, incomplete):
2019-01-07 17:51:19 +01:00
# You can generate completions with descriptions by returning
# tuples in the form (completion, description).
2020-07-21 08:23:42 +02:00
users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]
# Ths will allow completion matches based on matches within the
# description string too!
2019-01-07 17:51:19 +01:00
return [user for user in users if incomplete in user[0] or incomplete in user[1]]
2018-09-06 20:55:10 +02:00
2020-07-21 08:23:42 +02:00
@group.command(help="Choose a user")
2018-09-06 20:55:10 +02:00
@click.argument("user", type=click.STRING, autocompletion=list_users)
def subcmd(user):
2020-07-21 08:23:42 +02:00
click.echo("Chosen user is {}".format(user))
2018-09-06 20:55:10 +02:00
2019-01-07 17:51:19 +01:00
2018-09-06 20:55:10 +02:00
cli.add_command(group)