我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用click.pass_context()。
def list_modules(): module_list = [] get_all_modules('ansible.modules', module_list) return module_list # @cli.command('get-module') # @click.argument('module_name', nargs=1) # @click.pass_context # def get_module(ctx, module_name): # matches = [x for x in list_modules() if x.endswith(module_name)] # for m in matches: # path, name = m.rsplit('.',1) # module_info = read_module(m) # pprint.pprint(module_info["doc"]["options"]) # # info_all = read_package(path) # # module_info = info_all[0][name] # # yaml_text = yaml.dump(module_info["doc"]["options"], default_flow_style=False) # # print yaml_text
def unlockWallet(f): @click.pass_context def new_func(ctx, *args, **kwargs): if not ctx.obj.get("unsigned", False): if ctx.muse.wallet.created(): if "UNLOCK" in os.environ: pwd = os.environ["UNLOCK"] else: pwd = click.prompt("Current Wallet Passphrase", hide_input=True) ctx.muse.wallet.unlock(pwd) else: click.echo("No wallet installed yet. Creating ...") pwd = click.prompt("Wallet Encryption Passphrase", hide_input=True, confirmation_prompt=True) ctx.muse.wallet.create(pwd) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def make_django_command(name, django_command=None, help=None): "A wrapper to convert a Django subcommand a Click command" if django_command is None: django_command = name @click.command( name=name, help=help, add_help_option=False, context_settings=dict( ignore_unknown_options=True, )) @click.argument('management_args', nargs=-1, type=click.UNPROCESSED) @click.pass_context def inner(ctx, management_args): from munch.runner.commands.django import django ctx.params['management_args'] = (django_command,) + management_args ctx.forward(django) return inner
def catch_errors(func): """Decorator which catches all errors and tries to print them.""" @six.wraps(func) @click.pass_context def decorator(ctx, *args, **kwargs): try: return func(*args, **kwargs) except exceptions.DecapodAPIError as exc: utils.format_output_json(ctx, exc.json, True) except exceptions.DecapodError as exc: click.echo(six.text_type(exc), err=True) finally: ctx.close() ctx.exit(os.EX_SOFTWARE) return decorator
def run(func): """Execute the provided function if there are no subcommands""" @defaults.command(help='Run the service') @click.pass_context def runserver(ctx, *args, **kwargs): if (ctx.parent.invoked_subcommand and ctx.command.name != ctx.parent.invoked_subcommand): return # work around the fact that tornado's parse_command_line can't # cope with having subcommands / positional arguments. sys.argv = [sys.argv[0]] + [a for a in sys.argv if a[0] == '-'] sys.exit(func()) return runserver
def init(): """Return top level command handler.""" @click.command() @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) @click.option('--match', help='Server name pattern match') @click.pass_context def allocs(ctx, match): """View allocations report.""" report = fetch_report(ctx.obj.get('api'), 'allocations', match) report = report.loc[ ~report.name.str.startswith('_default/') ].reset_index(drop=True) print_report(report) return allocs
def init(): """Return top level command handler.""" @click.group(cls=cli.make_commands(__name__)) @click.pass_context def run(ctx): """Admin commands.""" cli.init_logger('admin.conf') log_level = logging.WARN if ctx.obj.get('logging.debug'): log_level = logging.DEBUG logging.getLogger('treadmill').setLevel(log_level) logging.getLogger().setLevel(log_level) return run
def store_vcs(f): """A decorator that store the VCS object into the object. """ # TODO ideally we should detect the type of VCS. # But for now, we only support git @click.pass_context @ensure_obj def new_func(ctx, *args, **kwargs): if 'vcs' in ctx.obj: return ctx.invoke(f, *args, **kwargs) # if not a repository, pass ``None`` try: vcs = GitVcs() except CommandError: vcs = None ctx.obj['vcs'] = vcs return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def store_api_client(f): """A decorator that stores the API client in context.obj """ @store_user @click.pass_context @ensure_obj def new_func(ctx, *args, **kwargs): if 'api_client' in ctx.obj: return ctx.invoke(f, *args, **kwargs) user = ctx.obj['user'] client = ApiClient( api_server_url=settings.API_SERVER_URL, username=user.username, api_key=user.api_key, ) ctx.obj['api_client'] = client return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def ensure_executable_exists(name, get_executable): """Ensures that the private executable exists. If it doesn't, then call get_executable, which must be a callable that installs the executable. """ def decorator(f): @click.pass_context def new_func(ctx, *args, **kwargs): """ @type ctx: click.Context """ path = path_utils.executable_path(name) if not os.path.exists(path): echo_heading('Installing {}.'.format(name), marker='-', marker_color='magenta') get_executable() assert os.path.exists(path) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f) return decorator
def make_django_command(name, django_command=None, help=None): "A wrapper to convert a Django subcommand a Click command" if django_command is None: django_command = name @click.command( name=name, help=help, add_help_option=False, context_settings=dict( ignore_unknown_options=True, )) @click.argument('management_args', nargs=-1, type=click.UNPROCESSED) @click.pass_context def inner(ctx, management_args): from {{ cookiecutter.module_name }}.runner.commands.django import django ctx.params['management_args'] = (django_command,) + management_args ctx.forward(django) return inner
def unlock(f): """ This decorator will unlock the wallet by either asking for a passphrase or taking the environmental variable ``UNLOCK`` """ @click.pass_context def new_func(ctx, *args, **kwargs): if not ctx.obj.get("unsigned", False): if ctx.bitshares.wallet.created(): if "UNLOCK" in os.environ: pwd = os.environ["UNLOCK"] else: pwd = click.prompt("Current Wallet Passphrase", hide_input=True) ctx.bitshares.wallet.unlock(pwd) else: click.echo("No wallet installed yet. Creating ...") pwd = click.prompt("Wallet Encryption Passphrase", hide_input=True, confirmation_prompt=True) ctx.bitshares.wallet.create(pwd) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def test_user_variables(self, command, files, output): @cli.command() @click.pass_context def noop(ctx): click.echo(yaml.safe_dump(ctx.obj["options"]["user_variables"])) self.patcher_getcwd.stop() with self.runner.isolated_filesystem(): for name, content in files.items(): with open(name, "w") as fh: yaml.safe_dump(content, fh) result = self.runner.invoke(cli, command) self.patcher_getcwd.start() user_variables = yaml.safe_load(result.output) assert result.exit_code == 0 assert user_variables == output
def unlockWallet(f): @click.pass_context def new_func(ctx, *args, **kwargs): if not ctx.obj.get("unsigned", False): if ctx.decent.wallet.created(): if "UNLOCK" in os.environ: pwd = os.environ["UNLOCK"] else: pwd = click.prompt("Current Wallet Passphrase", hide_input=True) ctx.decent.wallet.unlock(pwd) else: click.echo("No wallet installed yet. Creating ...") pwd = click.prompt("Wallet Encryption Passphrase", hide_input=True, confirmation_prompt=True) ctx.decent.wallet.create(pwd) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def make_django_command(name, django_command=None, help=None): "A wrapper to convert a Django subcommand a Click command" if django_command is None: django_command = name @click.command( name=name, help=help, add_help_option=False, context_settings=dict( ignore_unknown_options=True, )) @click.argument('management_args', nargs=-1, type=click.UNPROCESSED) @click.pass_context def inner(ctx, management_args): from sentry.runner.commands.django import django ctx.params['management_args'] = (django_command,) + management_args ctx.forward(django) return inner
def main(): if platform.system() == 'Windows': print "Lambkin doesn't run on Windows yet. Sorry." sys.exit(1) @click.group(invoke_without_command=True, no_args_is_help=True) @click.pass_context @click.option('--version', help='Show the version.', is_flag=True) def cli(ctx, version): if ctx.invoked_subcommand is None and version: click.echo(VERSION) subcommands = [create, list_published, build, publish, run, schedule, unpublish] for cmd in subcommands: cli.add_command(cmd) cli()
def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled. """ @click.pass_context def decorator(__ctx, *args, **kwargs): with __ctx.ensure_object(ScriptInfo).load_app().app_context(): return __ctx.invoke(f, *args, **kwargs) return update_wrapper(decorator, f)
def require_list(f): @wraps(f) @click.pass_context def wrapper(ctx, *args, **kwargs): try: ctx.obj.listobj = listobj.List(ctx.obj.list_address) except ( ValueError, ClientError, ): handle_invalid_list_address(ctx.obj.list_address) ctx.obj.listobj = None if ctx.obj.listobj is None: return return f(ctx, *args, **kwargs) return wrapper
def verbose(f): @click.pass_context def new_func(ctx, *args, **kwargs): global log verbosity = [ "critical", "error", "warn", "info", "debug" ][int(min(ctx.obj.get("verbose", 0), 4))] log.setLevel(getattr(logging, verbosity.upper())) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch = logging.StreamHandler() ch.setLevel(getattr(logging, verbosity.upper())) ch.setFormatter(formatter) log.addHandler(ch) # GrapheneAPI logging if ctx.obj["verbose"] > 4: verbosity = [ "critical", "error", "warn", "info", "debug" ][int(min(ctx.obj.get("verbose", 4) - 4, 4))] log = logging.getLogger("grapheneapi") log.setLevel(getattr(logging, verbosity.upper())) log.addHandler(ch) if ctx.obj["verbose"] > 8: verbosity = [ "critical", "error", "warn", "info", "debug" ][int(min(ctx.obj.get("verbose", 8) - 8, 4))] log = logging.getLogger("graphenebase") log.setLevel(getattr(logging, verbosity.upper())) log.addHandler(ch) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def offlineChain(f): @click.pass_context @verbose def new_func(ctx, *args, **kwargs): ctx.obj["offline"] = True ctx.muse = muse(**ctx.obj) set_shared_muse_instance(ctx.muse) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def onlineChain(f): @click.pass_context @verbose def new_func(ctx, *args, **kwargs): ctx.muse = muse(**ctx.obj) set_shared_muse_instance(ctx.muse) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def test_configfile__can_pass_additional_params_in_context(self, cli_runner_isolated): assert ConfigFileProcessor1.config_files[0] == "hello.ini" assert not os.path.exists("hello.cfg") CONFIG_FILE_CONTENTS = """ [hello] name = Alice [hello.more.foo] numbers = 1 2 3 [hello.more.bar] numbers = 1 """ write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS) assert os.path.exists("hello.ini") CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config()) @click.command(context_settings=CONTEXT_SETTINGS) @click.option("-n", "--name", default="__CMDLINE__") @click.pass_context def hello(ctx, name): click.echo("Hello %s" % name) hello_foo = ctx.default_map["foo"] hello_bar = ctx.default_map["bar"] click.echo("foo.numbers: %s" % repr(hello_foo["numbers"])) click.echo("bar.numbers: %s" % repr(hello_bar["numbers"])) assert os.path.exists("hello.ini") result = cli_runner_isolated.invoke(hello) expected_output = """\ Hello Alice foo.numbers: [1, 2, 3] bar.numbers: [1] """ assert result.output == expected_output assert result.exit_code == 0
def test_configfile__use_default_section_to_storage_name_mapping(self, cli_runner_isolated): assert ConfigFileProcessor2.config_files[0] == "hello2.ini" assert not os.path.exists("hello2.cfg") CONFIG_FILE_CONTENTS = """ [hello2] name = Alice [hello2.foo] numbers = 1 2 3 [hello2.bar] numbers = 42 """ write_configfile_with_contents("hello2.ini", CONFIG_FILE_CONTENTS) assert os.path.exists("hello2.ini") CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor2.read_config()) @click.command(context_settings=CONTEXT_SETTINGS) @click.option("-n", "--name", default="__CMDLINE__") @click.pass_context def hello2(ctx, name): click.echo("Hello2 %s" % name) hello2_foo = ctx.default_map["hello2.foo"] hello2_bar = ctx.default_map["hello2.bar"] click.echo("foo.numbers: %s" % repr(hello2_foo["numbers"])) click.echo("bar.numbers: %s" % repr(hello2_bar["numbers"])) assert os.path.exists("hello2.ini") result = cli_runner_isolated.invoke(hello2) expected_output = """\ Hello2 Alice foo.numbers: [1, 2, 3] bar.numbers: [42] """ assert result.output == expected_output assert result.exit_code == 0
def pass_context(func): """ Make click context ARIA specific. This exists purely for aesthetic reasons, otherwise some decorators are called ``@click.something`` instead of ``@aria.something``. """ return click.pass_context(func)
def _dynamic_rpc_cmd(self, ctx, cmd_name): @cli.command() @click.argument('params', nargs=-1, type=click.UNPROCESSED) @click.pass_context def _rpc_result(ctx, params): conf = ctx.parent.params['conf'] try: response = requests.post( 'http://%s:%s' % (conf['ethpconnect'], conf['ethpport']), data=json.dumps({ 'id': 'ethereum-cli', 'method': cmd_name, 'params': params, }) ) except requests.exceptions.ConnectionError: click.echo('error: couldn\'t connect to server: ' 'unknown (code -1)') click.echo('(make sure server is running and you are ' 'connecting to the correct RPC port)') return else: response = response.json() if response['error']: error = response['error'] click.echo('error code: %s' % error['code']) if error['code'] == -1: method = getattr(EthereumProxy, cmd_name) click.echo('error message:\n%s' % method.__doc__) else: click.echo('error message:\n%s' % error['message']) sys.exit(1) else: result = response['result'] if isinstance(result, Mapping): result = json.dumps(response['result'], indent=4) elif isinstance(result, bool): result = 'true' if result else 'false' click.echo(result) return click.Group.get_command(self, ctx, '_rpc_result')
def click_merge_parent_params(wrapped): @click.pass_context @functools.wraps(wrapped) def wrapper(ctx, **kwargs): if ctx.parent and ctx.parent.params: kwargs.update(ctx.parent.params) return wrapped(**kwargs) return wrapper
def configuration(f): import click from functools import update_wrapper @click.pass_context def inner(ctx, *args, **kwargs): # HACK: We can't call `configure()` from within tests # since we don't load config files from disk, so we # need a way to bypass this initialization step if os.environ.get('_MUNCH_SKIP_CONFIGURATION') != '1': from munch.runner import configure configure() return ctx.invoke(f, *args, **kwargs) return update_wrapper(inner, f)
def configfile(f): @click.pass_context def new_func(ctx, *args, **kwargs): ctx.config = yaml.load(open(ctx.obj["configfile"])) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
def dry_run(ctx, submission_dir): """ Test submission on submission folder(s). """ if '.' in submission_dir or '..' in submission_dir: ctx.obj['LOGGER'].critical("Submission dir can not be '.' or '..'") ctx.abort() utils.initialize_app(ctx) if not submission_dir: ctx.obj['LOGGER'].critical('You must specify at least one submission directory.') ctx.abort() perform_submission(ctx, submission_dir, dry_run=True) #@main.command() #@click.argument('submission_dir', type=click.Path(exists=True), nargs=-1) #@click.pass_context #def status(ctx, submission_dir): # """ # Report status of submission folder(s). # """ # if '.' in submission_dir or '..' in submission_dir: # ctx.obj['LOGGER'].critical("Submission dir can not be '.' or '..'") # ctx.abort() # utils.initialize_app(ctx) # generate_report(ctx, submission_dir)
def check_expose(func): @click.pass_context def _deco(ctx, *args, **kwargs): if not expose.enabled(): click.secho('warning: aeris.cd is not enabled', fg='yellow') sys.exit(1) try: return ctx.invoke(func, *args, **kwargs) except HTTPError as e: fatal(e.message) return update_wrapper(_deco, func)
def with_client(func): """Decorator which pass both client and model client to method.""" @six.wraps(func) @click.pass_context def decorator(ctx, *args, **kwargs): kwargs["client"] = ctx.obj["client"] return func(*args, **kwargs) return decorator
def format_output(func): """Decorator which formats output.""" @six.wraps(func) @click.pass_context def decorator(ctx, *args, **kwargs): response = func(*args, **kwargs) if not response: return if ctx.obj["format"] == "json": utils.format_output_json(ctx, response) return decorator