本文整理匯總了Python中click.MultiCommand方法的典型用法代碼示例。如果您正苦於以下問題:Python click.MultiCommand方法的具體用法?Python click.MultiCommand怎麽用?Python click.MultiCommand使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類click
的用法示例。
在下文中一共展示了click.MultiCommand方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: make_click_shell
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def make_click_shell(ctx, prompt=None, title=None, intro=None, hist_file=None):
assert isinstance(ctx, click.Context)
assert isinstance(ctx.command, click.MultiCommand)
# Set this to None so that it doesn't get printed out in usage messages
ctx.info_name = None
# Create our shell object
shell = MyClickShell(ctx=ctx, hist_file=hist_file)
if prompt is not None:
shell.prompt = prompt
if intro is not None:
shell.intro = intro
if title is not None:
shell.title = title
# Add all the commands
for name in ctx.command.list_commands(ctx):
command = ctx.command.get_command(ctx, name)
shell.add_command(command, name)
return shell
示例2: make_click_shell
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def make_click_shell(ctx, prompt=None, intro=None, hist_file=None):
assert isinstance(ctx, click.Context)
assert isinstance(ctx.command, click.MultiCommand)
# Set this to None so that it doesn't get printed out in usage messages
ctx.info_name = None
# Create our shell object
shell = ClickShell(ctx=ctx, hist_file=hist_file)
if prompt is not None:
shell.prompt = prompt
if intro is not None:
shell.intro = intro
# Add all the commands
for name in ctx.command.list_commands(ctx):
command = ctx.command.get_command(ctx, name)
shell.add_command(command, name)
return shell
示例3: get_choices
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def get_choices(cli, prog_name, args, incomplete):
"""
This is identical to click._bashcomplete:get_choices in click 6.4+
"""
ctx = resolve_ctx(cli, prog_name, args)
if ctx is None:
return
choices = []
if incomplete and not incomplete[:1].isalnum():
for param in ctx.command.params:
if not isinstance(param, click.Option):
continue
choices.extend(param.opts)
choices.extend(param.secondary_opts)
elif isinstance(ctx.command, click.MultiCommand):
choices.extend(ctx.command.list_commands(ctx))
for item in choices:
if item.startswith(incomplete):
yield item
示例4: format_options
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def format_options(self, ctx, formatter):
"""Writes all the options into the formatter if they exist."""
# Borrowed from click.MultiCommand
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
# rewrite for color
rv = list(rv)
rv[0] = click.style(rv[0], fg='green')
opts.append(tuple(rv))
if opts:
with formatter.section('Options'):
formatter.write_dl(opts)
示例5: format_commands
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def format_commands(self, ctx, formatter):
"""Extra format methods for multi methods that adds all the commands
after the options.
"""
# Borrowed from click.MultiCommand
commands = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
# What is this, the tool lied about a command. Ignore it
if cmd is None:
continue
if cmd.hidden:
continue
commands.append((subcommand, cmd))
# allow for 3 times the default spacing
if len(commands):
limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
rows = []
for subcommand, cmd in commands:
help = cmd.get_short_help_str(limit)
rows.append((subcommand, help))
for i, row in enumerate(rows): # rewrite for color
row = list(row)
row[0] = click.style(row[0], fg='green')
rows[i] = tuple(row)
if rows:
with formatter.section('Commands'):
formatter.write_dl(rows)
示例6: resolve_ctx
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def resolve_ctx(cli, prog_name, args, resilient_parsing=True):
"""
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
args : [str]
The arguments already written by the user on the command line
Returns
-------
click.core.Context
A new context corresponding to the current command
"""
ctx = cli.make_context(prog_name, list(args), resilient_parsing=resilient_parsing)
while ctx.args + ctx.protected_args and isinstance(ctx.command, MultiCommand):
a = ctx.protected_args + ctx.args
cmd = ctx.command.get_command(ctx, a[0])
if cmd is None:
return None
if hasattr(cmd, "no_args_is_help"):
no_args_is_help = cmd.no_args_is_help
cmd.no_args_is_help = False
ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=resilient_parsing)
if hasattr(cmd, "no_args_is_help"):
cmd.no_args_is_help = no_args_is_help
return ctx
示例7: format_commands
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def format_commands(self, ctx, formatter):
# Same as click.MultiCommand.format_commands except it does not use
# get_command so we don't have to load commands on listing.
rows = []
for subcommand in self.list_commands(ctx):
rows.append((subcommand, 'Run ' + subcommand))
if rows:
with formatter.section('Commands'):
formatter.write_dl(rows)
示例8: _filter_commands
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def _filter_commands(ctx, commands=None):
"""Return list of used commands."""
lookup = getattr(ctx.command, 'commands', {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key=lambda item: item.name)
names = [name.strip() for name in commands.split(',')]
return [lookup[name] for name in names if name in lookup]
示例9: initCommandUI
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def initCommandUI(self, func, run_exit, parent_layout=None):
opt_set = CommandLayout(func, run_exit, parent_layout=parent_layout)
if isinstance(func, click.MultiCommand):
tabs = _InputTabWidget()
for cmd, f in func.commands.items():
sub_opt_set = self.initCommandUI(f, run_exit, parent_layout=opt_set)
tab = QtWidgets.QWidget()
tab.setLayout(sub_opt_set)
tabs.addTab(tab, cmd)
opt_set.addWidget(
tabs, opt_set.rowCount(), 0, 1, 2
)
# return opt_set
elif isinstance(func, click.Command):
new_thread = getattr(func, "new_thread", self.new_thread)
opt_set.add_cmd_buttons( args=
[
{
'label':'&Run',
'cmd_slot': partial(self.run_cmd,\
new_thread=new_thread),
"tooltip":"run command"
},
{
'label':'&Copy',
'cmd_slot': self.copy_cmd,
"tooltip":"copy command to clipboard"
},
]
)
return opt_set
示例10: test_create
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def test_create(self):
shell = Shell()
assert isinstance(shell, click.MultiCommand)
示例11: make_commands
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def make_commands(section, **click_args):
"""Make a Click multicommand from all submodules of the module."""
class MCommand(click.MultiCommand):
"""Treadmill CLI driver."""
def __init__(self, *args, **kwargs):
if kwargs and click_args:
kwargs.update(click_args)
click.MultiCommand.__init__(self, *args, **kwargs)
def list_commands(self, ctx):
"""Return list of commands in section."""
return sorted(plugin_manager.names(section))
def get_command(self, ctx, cmd_name):
"""Return dymanically constructed command."""
try:
return plugin_manager.load(section, cmd_name).init()
except ImportError as import_err:
print(
'dependency error: {}:{} - {}'.format(
section, cmd_name, str(import_err)
),
file=sys.stderr
)
except KeyError:
raise click.UsageError('Invalid command: %s' % cmd_name)
return MCommand
示例12: get_completions
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def get_completions(self, document, complete_event=None):
# Code analogous to click._bashcomplete.do_complete
try:
args = shlex.split(document.text_before_cursor)
except ValueError:
# Invalid command, perhaps caused by missing closing quotation.
return
cursor_within_command = (
document.text_before_cursor.rstrip() == document.text_before_cursor
)
if args and cursor_within_command:
# We've entered some text and no space, give completions for the
# current word.
incomplete = args.pop()
else:
# We've not entered anything, either at all or for the current
# command, so give all relevant completions for this context.
incomplete = ""
ctx = click._bashcomplete.resolve_ctx(self.cli, "", args)
if ctx is None:
return
choices = []
for param in ctx.command.params:
if isinstance(param, click.Option):
for options in (param.opts, param.secondary_opts):
for o in options:
choices.append(
Completion(
text_type(o), -len(incomplete), display_meta=param.help
)
)
elif isinstance(param, click.Argument):
if isinstance(param.type, click.Choice):
for choice in param.type.choices:
choices.append(Completion(text_type(choice), -len(incomplete)))
if isinstance(ctx.command, click.MultiCommand):
for name in ctx.command.list_commands(ctx):
command = ctx.command.get_command(ctx, name)
choices.append(
Completion(
text_type(name),
-len(incomplete),
display_meta=getattr(command, "short_help"),
)
)
for item in choices:
if item.text.startswith(incomplete):
yield item
示例13: test_basics
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def test_basics(self):
"""Validate a custom ``click.MultiCommand`` with no parameters.
This exercises the code paths to extract commands correctly from these
commands.
"""
@click.command()
def hello():
"""A sample command."""
@click.command()
def world():
"""A world command."""
class MyCLI(click.MultiCommand):
_command_mapping = {
'hello': hello,
'world': world,
}
def list_commands(self, ctx):
return ['hello', 'world']
def get_command(self, ctx, name):
return self._command_mapping[name]
cli = MyCLI(help='A sample custom multicommand.')
ctx = click.Context(cli, info_name='cli')
output = list(ext._format_command(ctx, show_nested=False))
self.assertEqual(
textwrap.dedent("""
A sample custom multicommand.
.. program:: cli
.. code-block:: shell
cli [OPTIONS] COMMAND [ARGS]...
.. rubric:: Commands
.. object:: hello
A sample command.
.. object:: world
A world command.
""").lstrip(), '\n'.join(output))
示例14: test_hidden
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def test_hidden(self):
"""Ensure 'hidden' subcommands are not shown."""
@click.command()
def hello():
"""A sample command."""
@click.command()
def world():
"""A world command."""
@click.command(hidden=True)
def hidden():
"""A hidden command."""
class MyCLI(click.MultiCommand):
_command_mapping = {
'hello': hello,
'world': world,
'hidden': hidden,
}
def list_commands(self, ctx):
return ['hello', 'world', 'hidden']
def get_command(self, ctx, name):
return self._command_mapping[name]
cli = MyCLI(help='A sample custom multicommand.')
ctx = click.Context(cli, info_name='cli')
output = list(ext._format_command(ctx, show_nested=False))
# Note that we do NOT expect this to show the 'hidden' command
self.assertEqual(
textwrap.dedent("""
A sample custom multicommand.
.. program:: cli
.. code-block:: shell
cli [OPTIONS] COMMAND [ARGS]...
.. rubric:: Commands
.. object:: hello
A sample command.
.. object:: world
A world command.
""").lstrip(), '\n'.join(output))
示例15: parse_args
# 需要導入模塊: import click [as 別名]
# 或者: from click import MultiCommand [as 別名]
def parse_args(self, ctx, args):
from q2cli.core.config import CONFIG
if isinstance(self, click.MultiCommand):
return super().parse_args(ctx, args)
errors = []
parser = self.make_parser(ctx)
skip_rest = False
for _ in range(10): # surely this is enough attempts
try:
opts, args, param_order = parser.parse_args(args=args)
break
except click.ClickException as e:
errors.append(e)
skip_rest = True
if not skip_rest:
for param in click.core.iter_params_for_processing(
param_order, self.get_params(ctx)):
try:
value, args = param.handle_parse_result(ctx, opts, args)
except click.ClickException as e:
errors.append(e)
if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
errors.append(click.UsageError(
'Got unexpected extra argument%s (%s)'
% (len(args) != 1 and 's' or '',
' '.join(map(click.core.make_str, args)))))
if errors:
click.echo(ctx.get_help()+"\n", err=True)
if len(errors) > 1:
problems = 'There were some problems with the command:'
else:
problems = 'There was a problem with the command:'
click.echo(CONFIG.cfg_style('problem',
problems.center(78, ' ')), err=True)
for idx, e in enumerate(errors, 1):
msg = click.formatting.wrap_text(
e.format_message(),
initial_indent=' (%d/%d%s) ' % (idx, len(errors),
'?' if skip_rest else ''),
subsequent_indent=' ')
click.echo(CONFIG.cfg_style('error', msg), err=True)
ctx.exit(1)
ctx.args = args
return args