当前位置: 首页>>代码示例>>Python>>正文


Python click.Command方法代码示例

本文整理汇总了Python中click.Command方法的典型用法代码示例。如果您正苦于以下问题:Python click.Command方法的具体用法?Python click.Command怎么用?Python click.Command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在click的用法示例。


在下文中一共展示了click.Command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_hook

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def run_hook(self,
                 app: FlaskUnchained,
                 bundles: List[Bundle],
                 unchained_config: Optional[Dict[str, Any]] = None,
                 ) -> Dict[str, Union[click.Command, click.Group]]:
        """
        Discover CLI command and command groups from bundles and register them
        with the app.
        """
        commands = {}
        for bundle in bundles:
            command_groups = self.get_bundle_command_groups(bundle)
            commands.update(inherit_docstrings(command_groups, commands))
            commands.update(self.get_bundle_commands(bundle, command_groups))

        for name, command in commands.items():
            if name in app.cli.commands:
                warn(f'Command name conflict: "{name}" is taken.')
                continue
            app.cli.add_command(command, name)
        return commands 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:23,代码来源:register_commands_hook.py

示例2: __call__

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def __call__(self, func):
        module = sys.modules[func.__module__]

        # Get the command name as Django expects it
        self.name = func.__module__.rsplit(".", 1)[-1]

        # Build the click command
        decorators = [
            click.command(name=self.name, cls=self.cls, **self.kwargs),
        ] + self.get_params(self.name)

        for decorator in reversed(decorators):
            func = decorator(func)

        # Django expects the command to be callable (it instantiates the class
        # pointed at by the `Command` module-level property)...
        # ...let's make it happy.
        module.Command = lambda: func

        return func 
开发者ID:GaretJax,项目名称:django-click,代码行数:22,代码来源:adapter.py

示例3: get_command

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def get_command(self, ctx: click.Context, name: str) -> click.Command:
        """Return the relevant command given the context and name.

        .. warning::

            This differs substantially from Flask in that it allows
            for the inbuilt commands to be overridden.
        """
        info = ctx.ensure_object(ScriptInfo)
        command = None
        try:
            command = info.load_app().cli.get_command(ctx, name)
        except NoAppException:
            pass
        if command is None:
            command = super().get_command(ctx, name)
        return command 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:cli.py

示例4: profiler_arguments

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def profiler_arguments(f):
    @click.argument('argv', nargs=-1)
    @click.option('-m', 'module', type=Module(),
                  help='Run library module as a script.')
    @click.option('-c', 'command', type=Command(),
                  help='Program passed in as string.')
    @wraps(f)
    def wrapped(argv, module, command, **kwargs):
        if module is not None and command is not None:
            raise click.UsageError('Option -m and -c are exclusive')
        script = module or command
        if script is None:
            # -m and -c not passed.
            try:
                script_filename, argv = argv[0], argv[1:]
            except IndexError:
                raise click.UsageError('Script not specified')
            script = Script().convert(script_filename, None, None)
        kwargs.update(script=script, argv=argv)
        return f(**kwargs)
    return wrapped 
开发者ID:what-studio,项目名称:profiling,代码行数:23,代码来源:__main__.py

示例5: command

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def command(name=None, cls=None, **attrs):
    """
    Commands are the basic building block of command line interfaces in
    Click.  A basic command handles command line parsing and might dispatch
    more parsing to commands nested below it.

    :param name: the name of the command to use unless a group overrides it.
    :param context_settings: an optional dictionary with defaults that are
                             passed to the context object.
    :param params: the parameters to register with this command.  This can
                   be either :class:`Option` or :class:`Argument` objects.
    :param help: the help string to use for this command.
    :param epilog: like the help string but it's printed at the end of the
                   help page after everything else.
    :param short_help: the short help to use for this command.  This is
                       shown on the command listing of the parent command.
    :param add_help_option: by default each command registers a ``--help``
                            option.  This can be disabled by this parameter.
    :param options_metavar: The options metavar to display in the usage.
                            Defaults to ``[OPTIONS]``.
    :param args_before_options: Whether or not to display the options
                                        metavar before the arguments.
                                        Defaults to False.
    """
    return click.command(name=name, cls=cls or Command, **attrs) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:27,代码来源:click.py

示例6: get_bundle_commands

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def get_bundle_commands(self,
                            bundle: Bundle,
                            command_groups: Dict[str, click.Group],
                            ) -> Dict[str, click.Command]:
        # when a command belongs to a group, we don't also want to register the command.
        # therefore we collect all the command names belonging to groups, and use that
        # in our is_click_command type-checking fn below
        group_command_names = set(itertools.chain.from_iterable(
            g.commands.keys() for g in command_groups.values()))

        def is_click_command(obj: Any) -> bool:
            return self.is_click_command(obj) and obj.name not in group_command_names

        commands = {}
        for b in bundle._iter_class_hierarchy():
            for module in self.import_bundle_modules(b):
                new = self._collect_from_package(module, is_click_command)
                commands.update(inherit_docstrings(new, commands))
        return commands 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:21,代码来源:register_commands_hook.py

示例7: test_no_parameters

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def test_no_parameters(self):
        """Validate a `click.Command` with no parameters.

        This exercises the code paths for a command with *no* arguments, *no*
        options and *no* environment variables.
        """

        @click.command()
        def foobar():
            """A sample command."""
            pass

        ctx = click.Context(foobar, info_name='foobar')
        output = list(ext._format_command(ctx, show_nested=False))

        self.assertEqual(
            textwrap.dedent("""
        A sample command.

        .. program:: foobar
        .. code-block:: shell

            foobar [OPTIONS]
        """).lstrip(), '\n'.join(output)) 
开发者ID:click-contrib,项目名称:sphinx-click,代码行数:26,代码来源:test_formatter.py

示例8: _format_description

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def _format_description(ctx):
    """Format the description for a given `click.Command`.

    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    help_string = ctx.command.help or ctx.command.short_help
    if not help_string:
        return

    bar_enabled = False
    for line in statemachine.string2lines(help_string,
                                          tab_width=4,
                                          convert_whitespace=True):
        if line == '\b':
            bar_enabled = True
            continue
        if line == '':
            bar_enabled = False
        line = '| ' + line if bar_enabled else line
        yield line
    yield '' 
开发者ID:click-contrib,项目名称:sphinx-click,代码行数:24,代码来源:ext.py

示例9: _format_subcommand

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def _format_subcommand(command):
    """Format a sub-command of a `click.Command` or `click.Group`."""
    yield '.. object:: {}'.format(command.name)

    # click 7.0 stopped setting short_help by default
    if CLICK_VERSION < (7, 0):
        short_help = command.short_help
    else:
        short_help = command.get_short_help_str()

    if short_help:
        yield ''
        for line in statemachine.string2lines(short_help,
                                              tab_width=4,
                                              convert_whitespace=True):
            yield _indent(line) 
开发者ID:click-contrib,项目名称:sphinx-click,代码行数:18,代码来源:ext.py

示例10: _format_description

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def _format_description(ctx):
    """Format the description for a given `click.Command`.
    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    help_string = ctx.command.help or ctx.command.short_help
    if not help_string:
        return

    bar_enabled = False
    for line in statemachine.string2lines(
            help_string, tab_width=4, convert_whitespace=True):
        if line == '\b':
            bar_enabled = True
            continue
        if line == '':
            bar_enabled = False
        line = '| ' + line if bar_enabled else line
        yield line
    yield '' 
开发者ID:mirnylab,项目名称:cooler,代码行数:22,代码来源:make_cli_rst.py

示例11: get_command

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
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 
开发者ID:tencentyun,项目名称:scfcli,代码行数:22,代码来源:generate_event_action.py

示例12: get_help

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def get_help(command):
    """
    Get the Cmd help function from the click command
    :param command: The click Command object
    :return: the help_* method for Cmd
    :rtype: function
    """
    assert isinstance(command, click.Command)

    def help_(self):  # pylint: disable=unused-argument
        extra = {}
        for key, value in command.context_settings.items():
            if key not in extra:
                extra[key] = value

        # Print click's help message
        with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx:
            click.echo(ctx.get_help(), color=ctx.color)

    help_.__name__ = 'help_%s' % command.name
    return help_ 
开发者ID:clarkperkins,项目名称:click-shell,代码行数:23,代码来源:core.py

示例13: get_complete

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def get_complete(command):
    """
    Get the Cmd complete function for the click command
    :param command: The click Command object
    :return: the complete_* method for Cmd
    :rtype: function
    """

    assert isinstance(command, click.Command)

    def complete_(self, text, line, begidx, endidx):  # pylint: disable=unused-argument
        # Parse the args
        args = shlex.split(line[:begidx])
        # Strip of the first item which is the name of the command
        args = args[1:]

        # Then pass them on to the get_choices method that click uses for completion
        return [choice[0] if isinstance(choice, tuple) else choice
                for choice in get_choices(command, command.name, args, text)]

    complete_.__name__ = 'complete_%s' % command.name
    return complete_ 
开发者ID:clarkperkins,项目名称:click-shell,代码行数:24,代码来源:core.py

示例14: plugin_command_factory

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def plugin_command_factory():
    """Dynamically generate plugin groups for all plugins, and add all basic command to it"""
    for p in plugins.all():
        plugin_name = p.slug
        help = f"Options for '{plugin_name}'"
        group = click.Group(name=plugin_name, help=help)
        for name, description in CORE_COMMANDS.items():
            callback = func_factory(p, name)
            pretty_opt = click.Option(
                ["--pretty/--not-pretty"], help="Output a pretty version of the JSON"
            )
            params = [pretty_opt]
            command = click.Command(
                name,
                callback=callback,
                help=description.format(plugin_name),
                params=params,
            )
            group.add_command(command)

        plugins_group.add_command(group) 
开发者ID:Netflix-Skunkworks,项目名称:diffy,代码行数:23,代码来源:core.py

示例15: handle_shell_complete

# 需要导入模块: import click [as 别名]
# 或者: from click import Command [as 别名]
def handle_shell_complete(
    cli: click.Command, prog_name: str, complete_var: str, complete_instr: str
) -> bool:
    if "_" not in complete_instr:
        click.echo("Invalid completion instruction.", err=True)
        sys.exit(1)
    command, shell = complete_instr.split("_", 1)
    if command == "source":
        click.echo(
            get_completion_script(
                prog_name=prog_name, complete_var=complete_var, shell=shell
            )
        )
        return True
    elif command == "complete":
        return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)
    return False 
开发者ID:tiangolo,项目名称:typer,代码行数:19,代码来源:completion.py


注:本文中的click.Command方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。