Python click.Command() Examples
The following are 30
code examples of click.Command().
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: make_cli_rst.py From cooler with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 ''
Example #2
Source File: __main__.py From profiling with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #3
Source File: completion.py From typer with MIT License | 6 votes |
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
Example #4
Source File: adapter.py From django-click with MIT License | 6 votes |
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
Example #5
Source File: cli.py From quart with MIT License | 6 votes |
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
Example #6
Source File: core.py From click-shell with BSD 3-Clause "New" or "Revised" License | 6 votes |
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_
Example #7
Source File: core.py From click-shell with BSD 3-Clause "New" or "Revised" License | 6 votes |
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_
Example #8
Source File: register_commands_hook.py From flask-unchained with MIT License | 6 votes |
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
Example #9
Source File: register_commands_hook.py From flask-unchained with MIT License | 6 votes |
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
Example #10
Source File: generate_event_action.py From scfcli with Apache License 2.0 | 6 votes |
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 #11
Source File: test_formatter.py From sphinx-click with MIT License | 6 votes |
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))
Example #12
Source File: ext.py From sphinx-click with MIT License | 6 votes |
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 ''
Example #13
Source File: ext.py From sphinx-click with MIT License | 6 votes |
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)
Example #14
Source File: main.py From typer with MIT License | 5 votes |
def command( self, name: Optional[str] = None, *, cls: Optional[Type[click.Command]] = None, context_settings: Optional[Dict[Any, Any]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: str = "[OPTIONS]", add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, ) -> Callable[[CommandFunctionType], CommandFunctionType]: if cls is None: cls = TyperCommand def decorator(f: CommandFunctionType) -> CommandFunctionType: self.registered_commands.append( CommandInfo( name=name, cls=cls, context_settings=context_settings, callback=f, help=help, epilog=epilog, short_help=short_help, options_metavar=options_metavar, add_help_option=add_help_option, no_args_is_help=no_args_is_help, hidden=hidden, deprecated=deprecated, ) ) return f return decorator
Example #15
Source File: main.py From flytekit with Apache License 2.0 | 5 votes |
def _flyte_cli(ctx, host, project, domain, name, insecure): """ Command line tool for interacting with all entities on the Flyte Platform. """ pass ######################################################################################################################## # # Miscellaneous Commands # ########################################################################################################################
Example #16
Source File: launch_plan.py From flytekit with Apache License 2.0 | 5 votes |
def _get_command(self, ctx, lp, cmd_name): """ :param ctx: :param flytekit.common.launch_plan.SdkLaunchPlan lp: :rtype: click.Command """ pass
Example #17
Source File: main.py From typer with MIT License | 5 votes |
def get_group(typer_instance: Typer) -> click.Command: group = get_group_from_info(TyperInfo(typer_instance)) return group
Example #18
Source File: quick.py From quick with GNU General Public License v3.0 | 5 votes |
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
Example #19
Source File: core.py From diffy with Apache License 2.0 | 5 votes |
def add_plugins_args(f): """Adds installed plugin options.""" schemas = [] if isinstance(f, click.Command): for p in plugins.all(): schemas.append(get_plugin_properties(p.json_schema)) f.params.extend(params_factory(schemas)) else: if not hasattr(f, "__click_params__"): f.__click_params__ = [] for p in plugins.all(): schemas.append(get_plugin_properties(p.json_schema)) f.__click_params__.extend(params_factory(schemas)) return f
Example #20
Source File: completion.py From typer with MIT License | 5 votes |
def do_zsh_complete(cli: click.Command, prog_name: str) -> bool: completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") cwords = click.parser.split_arg_string(completion_args) args = cwords[1:] if args and not completion_args.endswith(" "): incomplete = args[-1] args = args[:-1] else: incomplete = "" def escape(s: str) -> str: return ( s.replace('"', '""') .replace("'", "''") .replace("$", "\\$") .replace("`", "\\`") ) res = [] for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete): if help: res.append(f'"{escape(item)}":"{escape(help)}"') else: res.append(f'"{escape(item)}"') if res: args_str = "\n".join(res) click.echo(f"_arguments '*: :(({args_str}))'") else: click.echo("_files") return True
Example #21
Source File: completion.py From typer with MIT License | 5 votes |
def do_fish_complete(cli: click.Command, prog_name: str) -> bool: completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "") cwords = click.parser.split_arg_string(completion_args) args = cwords[1:] if args and not completion_args.endswith(" "): incomplete = args[-1] args = args[:-1] else: incomplete = "" show_args = [] for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete): if help: formatted_help = re.sub(r"\s", " ", help) show_args.append(f"{item}\t{formatted_help}") else: show_args.append(item) if complete_action == "get-args": if show_args: for arg in show_args: click.echo(arg) elif complete_action == "is-args": if show_args: # Activate complete args (no files) sys.exit(0) else: # Deactivate complete args (allow files) sys.exit(1) return True
Example #22
Source File: magic.py From flask-react-spa with MIT License | 5 votes |
def is_click_command(obj): return isinstance(obj, click.Command) and not isinstance(obj, click.Group)
Example #23
Source File: completion.py From typer with MIT License | 5 votes |
def do_powershell_complete(cli: click.Command, prog_name: str) -> bool: completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "") cwords = click.parser.split_arg_string(completion_args) args = cwords[1:] for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete): click.echo(f"{item}:::{help or ' '}") return True
Example #24
Source File: completion.py From typer with MIT License | 5 votes |
def do_shell_complete(*, cli: click.Command, prog_name: str, shell: str) -> bool: if shell == "bash": return do_bash_complete(cli, prog_name) elif shell == "zsh": return do_zsh_complete(cli, prog_name) elif shell == "fish": return do_fish_complete(cli, prog_name) elif shell in {"powershell", "pwsh"}: return do_powershell_complete(cli, prog_name) return False
Example #25
Source File: make_cli_rst.py From cooler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _format_envvars(ctx): """Format all envvars for a `click.Command`.""" params = [x for x in ctx.command.params if getattr(x, 'envvar')] for param in params: yield '.. _{command_name}-{param_name}-{envvar}:'.format( command_name=ctx.command_path.replace(' ', '-'), param_name=param.name, envvar=param.envvar, ) yield '' for line in _format_envvar(param): yield line yield ''
Example #26
Source File: make_cli_rst.py From cooler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _format_arguments(ctx): """Format all `click.Argument` for a `click.Command`.""" params = [x for x in ctx.command.params if isinstance(x, click.Argument)] for param in params: for line in _format_argument(param): yield line yield ''
Example #27
Source File: make_cli_rst.py From cooler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _format_options(ctx): """Format all `click.Option` for a `click.Command`.""" # the hidden attribute is part of click 7.x only hence use of getattr params = [ x for x in ctx.command.params if isinstance(x, click.Option) and not getattr(x, 'hidden', False) ] for param in params: for line in _format_option(param): yield line yield ''
Example #28
Source File: make_cli_rst.py From cooler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _format_usage(ctx): """Format the usage for a `click.Command`.""" yield '.. code-block:: shell' yield '' for line in _get_usage(ctx).splitlines(): yield _indent(line) yield ''
Example #29
Source File: plugins.py From tutor with GNU Affero General Public License v3.0 | 5 votes |
def add_plugin_commands(command_group): """ Add commands provided by all plugins to the given command group. Each command is added with a name that is equal to the plugin name. """ for plugin in plugins.iter_installed(): if isinstance(plugin.command, click.Command): plugin.command.name = plugin.name command_group.add_command(plugin.command)
Example #30
Source File: core.py From click-shell with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def invoke_(self, arg): # pylint: disable=unused-argument try: command.main(args=shlex.split(arg), prog_name=command.name, standalone_mode=False, parent=self.ctx) except click.ClickException as e: # Show the error message e.show() except click.Abort: # We got an EOF or Keyboard interrupt. Just silence it pass except SystemExit: # Catch this an return the code instead. All of click's help commands do a sys.exit(), # and that's not ideal when running in a shell. pass except Exception as e: traceback.print_exception(type(e), e, None) logger.warning(traceback.format_exc()) # Always return False so the shell doesn't exit return False invoke_ = update_wrapper(invoke_, command.callback) invoke_.__name__ = 'do_%s' % command.name return invoke_