Python click.pass_context() Examples

The following are 30 code examples of click.pass_context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: test_click2cwl.py    From argparse2tool with Apache License 2.0 7 votes vote down vote up
def test_subparser(self):
        """
        Tests if tools with subparsers run without errors
        """
        @click.group()
        @click.pass_context
        @click.option('--debug', default=False)
        def cli(debug):
            pass

        @cli.command()
        @click.option('-s', '--some-option')
        def sync(some_option):
            pass

        @cli.command()
        @click.option('-o', '--some-other-option')
        def async(some_option):
            pass 
Example #2
Source File: cli.py    From jaide with GNU General Public License v2.0 6 votes vote down vote up
def interface_errors(ctx):
    """ Get any interface errors from the device.

    @param ctx: The click context paramter, for receiving the object dictionary
              | being manipulated by other previous functions. Needed by any
              | function with the @click.pass_context decorator.
    @type ctx: click.Context

    @returns: None. Functions part of click relating to the command group
            | 'main' do not return anything. Click handles passing context
            | between the functions and maintaing command order and chaining.
    """
    mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
    for ip in ctx.obj['hosts']:
        mp_pool.apply_async(wrap.open_connection, args=(ip,
                            ctx.obj['conn']['username'],
                            ctx.obj['conn']['password'],
                            wrap.interface_errors, [],
                            ctx.obj['out'],
                            ctx.obj['conn']['connect_timeout'],
                            ctx.obj['conn']['session_timeout'],
                            ctx.obj['conn']['port']), callback=write_out)
    mp_pool.close()
    mp_pool.join() 
Example #3
Source File: ui.py    From stakemachine with MIT License 6 votes vote down vote up
def unlock(f):
    @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) 
Example #4
Source File: cli.py    From jaide with GNU General Public License v2.0 6 votes vote down vote up
def device_info(ctx):
    """ Get basic device information.

    @param ctx: The click context paramter, for receiving the object dictionary
              | being manipulated by other previous functions. Needed by any
              | function with the @click.pass_context decorator.
    @type ctx: click.Context
    """
    mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
    for ip in ctx.obj['hosts']:
        mp_pool.apply_async(wrap.open_connection, args=(ip,
                            ctx.obj['conn']['username'],
                            ctx.obj['conn']['password'],
                            wrap.device_info, [],
                            ctx.obj['out'],
                            ctx.obj['conn']['connect_timeout'],
                            ctx.obj['conn']['session_timeout'],
                            ctx.obj['conn']['port']), callback=write_out)
    mp_pool.close()
    mp_pool.join() 
Example #5
Source File: __init__.py    From tmt with MIT License 6 votes vote down vote up
def base_command(cls, method_class=None, usage=None):
        """ Create base click command (common for all discover plugins) """

        # Prepare general usage message for the step
        if method_class:
            usage = Discover.usage(method_overview=usage)

        # Create the command
        @click.command(cls=method_class, help=usage)
        @click.pass_context
        @click.option(
            '-h', '--how', metavar='METHOD',
            help='Use specified method to discover tests.')
        def discover(context, **kwargs):
            context.obj.steps.add('discover')
            Discover._save_context(context)

        return discover 
Example #6
Source File: cli.py    From jaide with GNU General Public License v2.0 6 votes vote down vote up
def health_check(ctx):
    """ Get alarm and device health information.

    @param ctx: The click context paramter, for receiving the object dictionary
              | being manipulated by other previous functions. Needed by any
              | function with the @click.pass_context decorator.
    @type ctx: click.Context

    @returns: None. Functions part of click relating to the command group
            | 'main' do not return anything. Click handles passing context
            | between the functions and maintaing command order and chaining.
    """
    mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
    for ip in ctx.obj['hosts']:
        mp_pool.apply_async(wrap.open_connection, args=(ip,
                            ctx.obj['conn']['username'],
                            ctx.obj['conn']['password'],
                            wrap.health_check, [],
                            ctx.obj['out'],
                            ctx.obj['conn']['connect_timeout'],
                            ctx.obj['conn']['session_timeout'],
                            ctx.obj['conn']['port']), callback=write_out)
    mp_pool.close()
    mp_pool.join() 
Example #7
Source File: __init__.py    From tmt with MIT License 6 votes vote down vote up
def base_command(cls, method_class=None, usage=None):
        """ Create base click command (common for all report plugins) """

        # Prepare general usage message for the step
        if method_class:
            usage = Report.usage(method_overview=usage)

        # Create the command
        @click.command(cls=method_class, help=usage)
        @click.pass_context
        @click.option(
            '-h', '--how', metavar='METHOD',
            help='Use specified method for results reporting.')
        def report(context, **kwargs):
            context.obj.steps.add('report')
            Report._save_context(context)

        return report 
Example #8
Source File: __init__.py    From tmt with MIT License 6 votes vote down vote up
def base_command(cls, method_class=None, usage=None):
        """ Create base click command (common for all prepare plugins) """

        # Prepare general usage message for the step
        if method_class:
            usage = Prepare.usage(method_overview=usage)

        # Create the command
        @click.command(cls=method_class, help=usage)
        @click.pass_context
        @click.option(
            '-h', '--how', metavar='METHOD',
            help='Use specified method for environment preparation.')
        def prepare(context, **kwargs):
            context.obj.steps.add('prepare')
            Prepare._save_context(context)

        return prepare 
Example #9
Source File: __init__.py    From tmt with MIT License 6 votes vote down vote up
def base_command(cls, method_class=None, usage=None):
        """ Create base click command (common for all provision plugins) """

        # Prepare general usage message for the step
        if method_class:
            usage = Provision.usage(method_overview=usage)

        # Create the command
        @click.command(cls=method_class, help=usage)
        @click.pass_context
        @click.option(
            '-h', '--how', metavar='METHOD',
            help='Use specified method for provisioning.')
        def provision(context, **kwargs):
            context.obj.steps.add('provision')
            Provision._save_context(context)

        return provision 
Example #10
Source File: __init__.py    From tmt with MIT License 6 votes vote down vote up
def base_command(cls, method_class=None, usage=None):
        """ Create base click command (common for all finish plugins) """

        # Prepare general usage message for the step
        if method_class:
            usage = Finish.usage(method_overview=usage)

        # Create the command
        @click.command(cls=method_class, help=usage)
        @click.pass_context
        @click.option(
            '-h', '--how', metavar='METHOD',
            help='Use specified method for finishing tasks.')
        def finish(context, **kwargs):
            context.obj.steps.add('finish')
            Finish._save_context(context)

        return finish 
Example #11
Source File: decorators.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: generate_event_action.py    From scfcli with Apache License 2.0 6 votes vote down vote up
def get_command(self, ctx, cmd):

        if cmd not in self.srv_info:
            return None

        params = []
        for param in self.srv_info[cmd][self.PARAMS].keys():
            default = self.srv_info[cmd][self.PARAMS][param]["default"]
            params.append(click.Option(
                ["--{}".format(param)],
                default=default,
                help="Specify the {}, default is {}".format(param, default)
            ))

        cbfun = click.pass_context(self.action)
        cmd = click.Command(name=cmd,
                            short_help=self.srv_info[cmd]["help"],
                            params=params, callback=cbfun)

        return cmd 
Example #13
Source File: cli.py    From jaide with GNU General Public License v2.0 5 votes vote down vote up
def at_time_validate(ctx, param, value):
    """ Callback validating the at_time commit option.

    Purpose: Validates the `at time` option for the commit command. Only the
           | the following two formats are supported: 'hh:mm[:ss]' or
           | 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional).

    @param ctx: The click context paramter, for receiving the object dictionary
              | being manipulated by other previous functions. Needed by any
              | function with the @click.pass_context decorator. Callback
              | functions such as this one receive this automatically.
    @type ctx: click.Context
    @param param: param is passed into a validation callback function by click.
                | We do not use it.
    @type param: None
    @param value: The value that the user supplied for the at_time option.
    @type value: str

    @returns: The value that the user supplied, if it passed validation.
            | Otherwise, raises click.BadParameter
    @rtype: str
    """
    # if they are doing commit_at, ensure the input is formatted correctly.
    if value is not None:
        if (re.search(r'([0-2]\d)(:[0-5]\d){1,2}', value) is None and
            re.search(r'\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d(:[0-5]\d)?',
                      value) is None):
            raise click.BadParameter("A commit at time must be in one of the "
                                     "two formats: 'hh:mm[:ss]' or "
                                     "'yyyy-mm-dd hh:mm[:ss]' (seconds are "
                                     "optional).")
    ctx.obj['at_time'] = value
    return value 
Example #14
Source File: ethereum_cli.py    From ethereumd-proxy with MIT License 5 votes vote down vote up
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') 
Example #15
Source File: ui.py    From bitshares-pricefeed with MIT License 5 votes vote down vote up
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) 
Example #16
Source File: cli.py    From android_universal with MIT License 5 votes vote down vote up
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) 
Example #17
Source File: spawn.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def init():
    """Return top level command handler."""

    @click.command()
    @click.option('--run/--no-run', is_flag=True, default=False)
    @click.option('--treadmill-id', help='Treadmill admin user.')
    @click.pass_context
    def spawn(ctx, treadmill_id, run):
        """Installs Treadmill spawn."""
        ctx.obj['PARAMS']['zookeeper'] = context.GLOBAL.zk.url
        ctx.obj['PARAMS']['ldap'] = context.GLOBAL.ldap.url

        dst_dir = ctx.obj['PARAMS']['dir']
        profile = ctx.obj['PARAMS'].get('profile')

        bs_install.wipe(
            os.path.join(dst_dir, 'wipe_me'),
            os.path.join(dst_dir, 'bin', 'wipe_spawn.sh')
        )

        run_script = None
        if run:
            run_script = os.path.join(dst_dir, 'bin', 'run.sh')

        if treadmill_id:
            ctx.obj['PARAMS']['treadmillid'] = treadmill_id

        if not ctx.obj['PARAMS'].get('treadmillid'):
            raise click.UsageError(
                '--treadmill-id is required, '
                'unable to derive treadmill-id from context.')

        bs_install.install(
            'spawn',
            dst_dir,
            ctx.obj['PARAMS'],
            run=run_script,
            profile=profile,
        )

    return spawn 
Example #18
Source File: server.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def compact_view(func):
    @six.wraps(func)
    @click.option(
        "--compact", "-c",
        is_flag=True,
        help="Show server list in compact CSV view"
    )
    @click.pass_context
    def decorator(ctx, compact, *args, **kwargs):
        response = func(*args, **kwargs)
        if not compact or "filtered_set" in ctx.obj:
            return response
        return build_compact_server_response(response)

    return decorator 
Example #19
Source File: decorators.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
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 
Example #20
Source File: decorators.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
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 
Example #21
Source File: keystone.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def execute_if_enabled(func):
    @functools.wraps(func)
    @click.pass_context
    def decorator(ctx, *args, **kwargs):
        if CONF.auth_type != "keystone":
            LOG.info("Keystone integration is not enabled.")
            ctx.exit()

        return func(*args, **kwargs)

    return decorator 
Example #22
Source File: utils.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def ssh_command(func):
    func = click.option(
        "-i", "--identity-file",
        type=click.File(lazy=False),
        default=str(get_private_key_path()),
        help="Path to the private key file",
        show_default=True
    )(func)
    func = click.option(
        "-b", "--batch-size",
        type=int,
        default=20,
        help="By default, command won't connect to all servers "
             "simultaneously, it is trying to process servers in batches. "
             "Negative number or 0 means connect to all hosts",
        show_default=True,
    )(func)

    @functools.wraps(func)
    @click.pass_context
    def decorator(ctx, identity_file, batch_size, *args, **kwargs):
        private_key = asyncssh.import_private_key(identity_file.read())
        batch_size = batch_size if batch_size > 0 else None
        identity_file.close()

        ctx.obj["private_key"] = private_key
        ctx.obj["batch_size"] = batch_size
        ctx.obj["event_loop"] = asyncio.get_event_loop()

        return func(*args, **kwargs)

    return decorator 
Example #23
Source File: cli.py    From elevation with Apache License 2.0 5 votes vote down vote up
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 
Example #24
Source File: master.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def init():
    """Return top level command handler."""

    @click.command()
    @click.option('--run/--no-run', is_flag=True, default=False)
    @click.option('--master-id', required=True,
                  type=click.Choice(['1', '2', '3']))
    @click.pass_context
    def master(ctx, run, master_id):
        """Installs Treadmill master."""

        ctx.obj['PARAMS']['zookeeper'] = context.GLOBAL.zk.url
        ctx.obj['PARAMS']['ldap'] = context.GLOBAL.ldap.url
        ctx.obj['PARAMS']['master_id'] = master_id
        dst_dir = ctx.obj['PARAMS']['dir']
        profile = ctx.obj['PARAMS'].get('profile')

        for master in ctx.obj['PARAMS']['masters']:  # pylint: disable=E1136
            if int(master['idx']) == int(master_id):
                ctx.obj['PARAMS'].update({'me': master})

        run_sh = None
        if run:
            run_sh = os.path.join(dst_dir, 'treadmill', 'bin', 'run.sh')

        bs_install.install(
            'master',
            dst_dir,
            ctx.obj['PARAMS'],
            run=run_sh,
            profile=profile,
        )

    return master 
Example #25
Source File: __init__.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def init():
    """Return top level command handler."""

    @click.group(cls=cli.make_commands(__name__))
    @click.pass_context
    def run(_ctxp):
        """Manage Local node and container diagnostics.
        """

    return run 
Example #26
Source File: ui.py    From stakemachine with MIT License 5 votes vote down vote up
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) 
Example #27
Source File: ui.py    From stakemachine with MIT License 5 votes vote down vote up
def chain(f):
    @click.pass_context
    def new_func(ctx, *args, **kwargs):
        ctx.bitshares = BitShares(
            ctx.config["node"],
            **ctx.obj
        )
        set_shared_bitshares_instance(ctx.bitshares)
        return ctx.invoke(f, *args, **kwargs)
    return update_wrapper(new_func, f) 
Example #28
Source File: ui.py    From stakemachine with MIT License 5 votes vote down vote up
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) 
Example #29
Source File: cli.py    From quart with MIT License 5 votes vote down vote up
def with_appcontext(fn: Optional[Callable] = None) -> Callable:
    # decorator was used with parenthesis
    if fn is None:
        return with_appcontext

    @click.pass_context
    def decorator(__ctx: click.Context, *args: Any, **kwargs: Any) -> Any:
        async def _inner() -> Any:
            async with __ctx.ensure_object(ScriptInfo).load_app().app_context():
                return __ctx.invoke(fn, *args, **kwargs)

        return asyncio.run(_inner())

    return functools.update_wrapper(decorator, fn) 
Example #30
Source File: cli.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
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)