本文整理汇总了Python中click.Group方法的典型用法代码示例。如果您正苦于以下问题:Python click.Group方法的具体用法?Python click.Group怎么用?Python click.Group使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.Group方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: list_commands
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def list_commands(self, ctx):
self._load_plugin_commands()
# The commands available is the list of both the application (if
# available) plus the builtin commands.
rv = set(click.Group.list_commands(self, ctx))
info = ctx.ensure_object(ScriptInfo)
try:
rv.update(info.load_app().cli.list_commands(ctx))
except Exception:
# Here we intentionally swallow all exceptions as we don't
# want the help page to break if the app does not exist.
# If someone attempts to use the command we try to create
# the app again and this will give us the error.
# However, we will not do so silently because that would confuse
# users.
traceback.print_exc()
return sorted(rv)
示例2: list_commands
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def list_commands(self, ctx):
self._load_plugin_commands()
# The commands available is the list of both the application (if
# available) plus the builtin commands.
rv = set(click.Group.list_commands(self, ctx))
info = ctx.ensure_object(ScriptInfo)
try:
rv.update(info.load_app().cli.list_commands(ctx))
except Exception:
# Here we intentionally swallow all exceptions as we don't
# want the help page to break if the app does not exist.
# If someone attempts to use the command we try to create
# the app again and this will give us the error.
pass
return sorted(rv)
示例3: command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def command(self, *args, **kwargs):
"""Behaves the same as `click.Group.command()` except if passed
a list of names, all after the first will be aliases for the first.
"""
def decorator(f):
if args and isinstance(args[0], list):
_args = [args[0][0]] + list(args[1:])
for alias in args[0][1:]:
cmd = super(CustomMultiCommand, self).command(
alias, *args[1:], **kwargs)(f)
cmd.short_help = "Alias for '{}'".format(_args[0])
else:
_args = args
cmd = super(CustomMultiCommand, self).command(
*_args, **kwargs)(f)
return cmd
return decorator
示例4: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_command(self, ctx, cmd_name):
"""
Allows commands to be called by their first unique character
:param ctx: Context information from click
:param cmd_name: Calling command name
:return:
"""
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
# Create the help option for CLICK
示例5: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_command(self, ctx, cmd_name):
"""Allow aliases for commands.
"""
if cmd_name == 'list':
cmd_name = 'ls'
elif cmd_name == 'search':
cmd_name = 'find'
elif cmd_name == 'gen':
cmd_name = 'generate'
elif cmd_name == 'add':
cmd_name = 'insert'
elif cmd_name in ['remove', 'delete']:
cmd_name = 'rm'
elif cmd_name == 'rename':
cmd_name = 'mv'
elif cmd_name == 'copy':
cmd_name = 'cp'
# TODO(benedikt) Figure out how to make 'show' the default
# command and pass cmd_name as the first argument.
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
示例6: group
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def group(name=None, cls=None, **attrs):
"""
A group allows a command to have subcommands attached. This is the
most common way to implement nesting in Click.
:param name: the name of the group (optional)
:param commands: a dictionary of commands.
: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 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.
"""
return click.group(name=name, cls=cls or Group, **attrs)
示例7: run_hook
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [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
示例8: get_bundle_commands
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [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
示例9: get_bundle_command_groups
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_bundle_command_groups(self, bundle: Bundle) -> Dict[str, click.Group]:
command_groups = {}
module_found = False
for b in bundle._iter_class_hierarchy():
for module in self.import_bundle_modules(b):
module_found = True
command_groups.update(
self._collect_from_package(module, self.is_click_group)
)
groups = {}
for name in getattr(bundle, 'command_group_names', [bundle.name]):
try:
groups[name] = command_groups[name]
except KeyError as e:
if module_found and not bundle.is_single_module:
warn(f'WARNING: Found a commands module for the {bundle.name} '
f'bundle, but there was no command group named {e.args[0]}'
f' in it. Either create one, or customize the bundle\'s '
f'`command_group_names` class attribute.')
continue
return groups
示例10: test_no_parameters
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def test_no_parameters(self):
"""Validate a `click.Group` with no parameters.
This exercises the code paths for a group with *no* arguments, *no*
options and *no* environment variables.
"""
@click.group()
def cli():
"""A sample command group."""
pass
ctx = click.Context(cli, info_name='cli')
output = list(ext._format_command(ctx, show_nested=False))
self.assertEqual(
textwrap.dedent("""
A sample command group.
.. program:: cli
.. code-block:: shell
cli [OPTIONS] COMMAND [ARGS]...
""").lstrip(), '\n'.join(output))
示例11: _format_subcommand
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [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)
示例12: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_command(self, context, cmd_name):
""" Allow command shortening """
# Backward-compatible 'test convert' (just temporary for now FIXME)
cmd_name = cmd_name.replace('convert', 'import')
# Support both story & stories
cmd_name = cmd_name.replace('story', 'stories')
found = click.Group.get_command(self, context, cmd_name)
if found is not None:
return found
matches = [command for command in self.list_commands(context)
if command.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, context, matches[0])
context.fail('Did you mean {}?'.format(
listed(sorted(matches), join='or')))
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Common Options
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
示例13: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_command(self,ctx,cmd_name):
"""
Allows commands to be called by their first unique character
:param ctx: Context information from click
:param cmd_name: Calling command name
:return:
"""
command = click.Group.get_command(self,ctx,cmd_name)
if command is not None:
return command
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self,ctx,matches[0])
ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))
# That's right, we support -h and --help! Not using -h for an argument like 'host'! ;D
示例14: plugin_command_factory
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [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)
示例15: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Group [as 别名]
def get_command(typer_instance: Typer) -> click.Command:
if typer_instance._add_completion:
click_install_param, click_show_param = get_install_completion_arguments()
if (
typer_instance.registered_callback
or typer_instance.info.callback
or typer_instance.registered_groups
or len(typer_instance.registered_commands) > 1
):
# Create a Group
click_command = get_group(typer_instance)
if typer_instance._add_completion:
click_command.params.append(click_install_param)
click_command.params.append(click_show_param)
return click_command
elif len(typer_instance.registered_commands) == 1:
# Create a single Command
click_command = get_command_from_info(typer_instance.registered_commands[0])
if typer_instance._add_completion:
click_command.params.append(click_install_param)
click_command.params.append(click_show_param)
return click_command
assert False, "Could not get a command for this Typer instance" # pragma no cover