Python click.Argument() Examples

The following are 23 code examples of click.Argument(). 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: method_terminal_commands.py    From cellphonedb with MIT License 6 votes vote down vote up
def check_subsampling_params(ctx: Context, argument: Argument, value) -> Any:
    subsampling = ctx.params.get('subsampling')

    if not subsampling and value is not None:
        tpl = 'This parameter ({}) only applies to subsampling, to enable it add `--subsampling` to your command'
        app_logger.error(tpl.format(argument.name))
        ctx.abort()

    if argument.name == 'subsampling_log' and subsampling and value is None:
        app_logger.error('''In order to perform subsampling you need to specify whether to log1p input counts or not:
            to do this specify in your command as --subsampling-log [true|false]''')
        ctx.abort()

    defaults = {
        'subsampling_num_pc': 100,
        'subsampling_num_cells': None
    }

    if subsampling and value is None:
        return defaults.get(argument.name, None)

    return value 
Example #2
Source File: runs_import.py    From guildai with Apache License 2.0 6 votes vote down vote up
def import_params(fn):
    click_util.append_params(
        fn,
        [
            runs_support.runs_arg,
            click.Argument(("archive",)),
            click.Option(
                ("-m", "--move"),
                help="Move imported runs rather than copy.",
                is_flag=True,
            ),
            click.Option(
                ("--copy-resources",),
                help="Copy resources for each imported run.",
                is_flag=True,
            ),
            runs_support.all_filters,
            click.Option(
                ("-y", "--yes"), help="Do not prompt before importing.", is_flag=True
            ),
        ],
    )
    return fn 
Example #3
Source File: runs_support.py    From guildai with Apache License 2.0 6 votes vote down vote up
def runs_arg(fn):
    """### Specify Runs

    You may use one or more `RUN` arguments to indicate which runs
    apply to the command. `RUN` may be a run ID, a run ID prefix, or a
    one-based index corresponding to a run returned by the list
    command.

    Indexes may also be specified in ranges in the form `START:END`
    where `START` is the start index and `END` is the end
    index. Either `START` or `END` may be omitted. If `START` is
    omitted, all runs up to `END` are selected. If `END` id omitted,
    all runs from `START` on are selected. If both `START` and `END`
    are omitted (i.e. the ``:`` char is used by itself) all runs are
    selected.

    """
    click_util.append_params(
        fn, [click.Argument(("runs",), metavar="[RUN...]", nargs=-1)]
    )
    return fn 
Example #4
Source File: click.py    From flask-unchained with MIT License 6 votes vote down vote up
def format_options(self, ctx, formatter):
        args = []
        opts = []
        for param in self.get_params(ctx):
            rv = param.get_help_record(ctx)
            if rv is not None:
                if isinstance(param, click.Argument):
                    args.append(rv)
                else:
                    opts.append(rv)
        if args:
            with formatter.section('Arguments'):
                formatter.write_dl(args)
        if opts:
            with formatter.section(self.options_metavar):
                formatter.write_dl(opts)

    # overridden to set the limit parameter to always be CLI_HELP_STRING_MAX_LEN 
Example #5
Source File: main.py    From typer with MIT License 5 votes vote down vote up
def get_params_convertors_ctx_param_name_from_function(
    callback: Optional[Callable[..., Any]]
) -> Tuple[List[Union[click.Argument, click.Option]], Dict[str, Any], Optional[str]]:
    params = []
    convertors = {}
    context_param_name = None
    if callback:
        parameters = get_params_from_function(callback)
        for param_name, param in parameters.items():
            if lenient_issubclass(param.annotation, click.Context):
                context_param_name = param_name
                continue
            click_param, convertor = get_click_param(param)
            if convertor:
                convertors[param_name] = convertor
            params.append(click_param)
    return params, convertors, context_param_name 
Example #6
Source File: runs_support.py    From guildai with Apache License 2.0 5 votes vote down vote up
def run_arg(fn):
    """### Specify a Run

    You may specify a run using a run ID, a run ID prefix, or a
    one-based index corresponding to a run returned by the `list`
    command.

    """
    click_util.append_params(fn, [click.Argument(("run",), required=False)])
    return fn 
Example #7
Source File: remote_support.py    From guildai with Apache License 2.0 5 votes vote down vote up
def remote_arg(fn):
    """`REMOTE` is the name of a configured remote. Use ``guild remotes``
    to list available remotes.

    For information on configuring remotes, see ``guild remotes
    --help``.

    """
    click_util.append_params(fn, [click.Argument(("remote",))])
    return fn 
Example #8
Source File: packages_delete.py    From guildai with Apache License 2.0 5 votes vote down vote up
def delete_params(fn):
    click_util.append_params(
        fn,
        [
            click.Argument(
                ("packages",), metavar="PACKAGE...", nargs=-1, required=True
            ),
            click.Option(
                ("-y", "--yes",),
                help="Do not prompt before uninstalling.",
                is_flag=True,
            ),
        ],
    )
    return fn 
Example #9
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_envvar(param):
    """Format the envvars of a `click.Option` or `click.Argument`."""
    yield '.. envvar:: {}'.format(param.envvar)
    yield '   :noindex:'
    yield ''
    if isinstance(param, click.Argument):
        param_ref = param.human_readable_name
    else:
        # if a user has defined an opt with multiple "aliases", always use the
        # first. For example, if '--foo' or '-f' are possible, use '--foo'.
        param_ref = param.opts[0]

    yield _indent('Provide a default for :option:`{}`'.format(param_ref)) 
Example #10
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #11
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_argument(arg):
    """Format the output of a `click.Argument`."""
    yield '.. option:: {}'.format(arg.human_readable_name)
    yield ''
    yield _indent('{} argument{}'.format(
        'Required' if arg.required else 'Optional', '(s)'
        if arg.nargs != 1 else '')) 
Example #12
Source File: ext.py    From sphinx-click with MIT License 5 votes vote down vote up
def _format_envvar(param):
    """Format the envvars of a `click.Option` or `click.Argument`."""
    yield '.. envvar:: {}'.format(param.envvar)
    yield '   :noindex:'
    yield ''
    if isinstance(param, click.Argument):
        param_ref = param.human_readable_name
    else:
        # if a user has defined an opt with multiple "aliases", always use the
        # first. For example, if '--foo' or '-f' are possible, use '--foo'.
        param_ref = param.opts[0]

    yield _indent('Provide a default for :option:`{}`'.format(param_ref)) 
Example #13
Source File: ext.py    From sphinx-click with MIT License 5 votes vote down vote up
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 #14
Source File: ext.py    From sphinx-click with MIT License 5 votes vote down vote up
def _format_argument(arg):
    """Format the output of a `click.Argument`."""
    yield '.. option:: {}'.format(arg.human_readable_name)
    yield ''
    yield _indent('{} argument{}'.format(
        'Required' if arg.required else 'Optional',
        '(s)' if arg.nargs != 1 else '')) 
Example #15
Source File: click.py    From flask-unchained with MIT License 5 votes vote down vote up
def argument(*param_decls, cls=None, **attrs):
    """
    Arguments are positional parameters to a command.  They generally
    provide fewer features than options but can have infinite ``nargs``
    and are required by default.

    :param param_decls: the parameter declarations for this option or
                        argument.  This is a list of flags or argument
                        names.
    :param type: the type that should be used.  Either a :class:`ParamType`
                 or a Python type.  The later is converted into the former
                 automatically if supported.
    :param required: controls if this is optional or not.
    :param default: the default value if omitted.  This can also be a callable,
                    in which case it's invoked when the default is needed
                    without any arguments.
    :param callback: a callback that should be executed after the parameter
                     was matched.  This is called as ``fn(ctx, param,
                     value)`` and needs to return the value.  Before Click
                     2.0, the signature was ``(ctx, value)``.
    :param nargs: the number of arguments to match.  If not ``1`` the return
                  value is a tuple instead of single value.  The default for
                  nargs is ``1`` (except if the type is a tuple, then it's
                  the arity of the tuple).
    :param metavar: how the value is represented in the help page.
    :param expose_value: if this is `True` then the value is passed onwards
                         to the command callback and stored on the context,
                         otherwise it's skipped.
    :param is_eager: eager values are processed before non eager ones.  This
                     should not be set for arguments or it will inverse the
                     order of processing.
    :param envvar: a string or list of strings that are environment variables
                   that should be checked.
    :param help: the help string.
    :param hidden: hide this option from help outputs.
                   Default is True, unless help is given.
    """
    return click.argument(*param_decls, cls=cls or Argument, **attrs) 
Example #16
Source File: click.py    From flask-unchained with MIT License 5 votes vote down vote up
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) 
Example #17
Source File: click.py    From flask-unchained with MIT License 5 votes vote down vote up
def command(self, *args, **kwargs):
        """
        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.
        """
        kwargs.setdefault('cls', Command)
        return super().command(*args, **kwargs) 
Example #18
Source File: choose_database.py    From cellphonedb with MIT License 5 votes vote down vote up
def choose_database(ctx: Context, argument: Argument, value: str) -> Optional[str]:
    return DatabaseVersionManager.find_database_for(value) 
Example #19
Source File: __main__.py    From civis-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def add_command_params(cmd, op_dict):
    """Add parameters to the click command for an API operation."""

    # Extract properties of objects in body to make click params for them.
    parameters_orig = op_dict.get('parameters', [])
    parameters = []
    for p in parameters_orig:
        if p['in'] == 'body':
            body_params = []
            req = p['schema'].get('required', [])
            for prop_name, prop_info in p['schema']['properties'].items():
                p_new = dict(
                    name=camel_to_snake(prop_name),
                    type=prop_info['type'],
                    description=prop_info.get('description', ''),
                    required=req == 'all' or prop_name in req,
                )
                body_params.append(p_new)

            # Sort the parameters since they don't have an order as properties.
            body_params = sorted(body_params, key=lambda x: x['name'])

            parameters.extend(body_params)
        else:
            parameters.append(p)

    # Specify the parameters for this command.
    for p in parameters:
        param_type_spec = p.get('type', 'string')
        param_type = _TYPE_MAP[param_type_spec]
        description = p.get('description', '')

        if p['required']:
            cmd.help += "\n\n{} ({}) - {}".format(
                p['name'].upper(), param_type_spec, description)
            arg = click.Argument([p['name'].lower()],
                                 type=param_type)
            cmd.params.append(arg)
        else:
            arg = click.Option(['--' + munge_name(p['name'].lower())],
                               help=description,
                               type=param_type)
            cmd.params.append(arg) 
Example #20
Source File: __main__.py    From pifpaf with Apache License 2.0 4 votes vote down vote up
def get_command(self, ctx, name):
        params = [click.Argument(["command"], nargs=-1)]
        plugin = pkg_resources.load_entry_point(
            "pifpaf", "pifpaf.daemons", name)
        params.extend(map(lambda kw: click.Option(**kw), plugin.get_options()))

        def _run_cb(*args, **kwargs):
            return self._run(name, plugin, ctx, *args, **kwargs)

        return click.Command(name=name, callback=_run_cb, params=params) 
Example #21
Source File: dynamic_click.py    From notifiers with MIT License 4 votes vote down vote up
def params_factory(schema: dict, add_message: bool) -> list:
    """
    Generates list of :class:`click.Option` based on a JSON schema

    :param schema:  JSON schema to operate on
    :return: Lists of created :class:`click.Option` object to be added to a :class:`click.Command`
    """

    # Immediately create message as an argument
    params = []
    if add_message:
        params.append(click.Argument(["message"], required=False))

    for property, prpty_schema in schema.items():
        multiple = False
        choices = None

        if any(char in property for char in ["@"]):
            continue
        if prpty_schema.get("type") in COMPLEX_TYPES:
            continue
        if prpty_schema.get("duplicate"):
            continue
        if property == "message":
            continue

        elif not prpty_schema.get("oneOf"):
            click_type, description, choices = json_schema_to_click_type(prpty_schema)
        else:
            click_type, multiple, description = handle_oneof(prpty_schema["oneOf"])
            # Not all oneOf schema can be handled by click
            if not click_type:
                continue

        # Convert bool values into flags
        if click_type == click.BOOL:
            param_decls = [get_flag_param_decals_from_bool(property)]
            click_type = None
        else:
            param_decls = [get_param_decals_from_name(property)]

        if description:
            description = description.capitalize()

            if multiple:
                if not description.endswith("."):
                    description += "."
                description += " Multiple usages of this option are allowed"
        # Construct the base command options
        option = partial(
            click.Option, param_decls=param_decls, help=description, multiple=multiple
        )

        if choices:
            option = option(type=choices)
        elif click_type:
            option = option(type=click_type)
        else:
            option = option()
        params.append(option)
    return params 
Example #22
Source File: runs_diff.py    From guildai with Apache License 2.0 4 votes vote down vote up
def diff_params(fn):
    click_util.append_params(
        fn,
        [
            click.Argument(("runs",), metavar="[RUN1 [RUN2]]", nargs=-1),
            click.Option(("-O", "--output"), is_flag=True, help="Diff run output."),
            click.Option(
                ("-s", "--sourcecode"), is_flag=True, help="Diff run source code."
            ),
            click.Option(("-e", "--env"), is_flag=True, help="Diff run environment."),
            click.Option(("-f", "--flags"), is_flag=True, help="Diff run flags."),
            click.Option(
                ("-a", "--attrs"),
                is_flag=True,
                help=(
                    "Diff all run attributes; if specified other "
                    "attribute options are ignored."
                ),
            ),
            click.Option(("-d", "--deps"), is_flag=True, help="Diff run dependencies."),
            click.Option(
                ("-p", "--path"),
                metavar="PATH",
                multiple=True,
                help="Diff specified path; may be used more than once.",
            ),
            click.Option(
                ("-w", "--working"),
                is_flag=True,
                help="Diff run sourcecode to the associated working directory.",
            ),
            click.Option(
                ("-W", "--working-dir"),
                metavar="PATH",
                help="Diff run sourcecode to the specified directory.",
            ),
            click.Option(
                ("-c", "--cmd"), metavar="CMD", help="Command used to diff runs."
            ),
            runs_support.all_filters,
            remote_support.remote_option("Diff remote runs."),
        ],
    )
    return fn 
Example #23
Source File: __init__.py    From click-repl with MIT License 4 votes vote down vote up
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