本文整理匯總了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
示例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
示例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
示例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
示例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)
示例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
示例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))
示例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 ''
示例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)
示例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 ''
示例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
示例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_
示例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_
示例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)
示例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