cli.py
This file
Path
examples/complex/complex/cli.py
64 lines · 1.8 KiB · Python
Last changed by
defaults -> settingsArmin Ronacherbefore adoption1bc0a19
History of this fileTake it
1import os2import sys3import click456CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')789class Context(object):1011 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()1415 def log(self, msg, *args):16 """Logs a message to stderr."""17 if args:18 msg %= args19 click.echo(msg, file=sys.stderr)2021 def vlog(self, msg, *args):22 """Logs a message to stderr only if verbose is enabled."""23 if self.verbose:24 self.log(msg, *args)252627pass_context = click.make_pass_decorator(Context, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),29 'commands'))303132class ComplexCLI(click.MultiCommand):3334 def list_commands(self, ctx):35 rv = []36 for filename in os.listdir(cmd_folder):37 if filename.endswith('.py') and \38 filename.startswith('cmd_'):39 rv.append(filename[4:-3])40 rv.sort()41 return rv4243 def get_command(self, ctx, name):44 try:45 mod = __import__('complex.commands.cmd_' +46 name.encode('ascii', 'replace'),47 None, None, ['cli'])48 except ImportError:49 return50 return mod.cli515253@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)54@click.option('--home', type=click.Path(exists=True, file_okay=False,55 resolve_path=True),56 help='Changes the folder to operate on.')57@click.option('-v', '--verbose', is_flag=True,58 help='Enables verbose mode.')59@pass_context60def cli(ctx, verbose, home):61 """A complex command line interface."""62 ctx.verbose = verbose63 if home is not None:64 ctx.home = home