How to use the argcomplete.CompletionFinder function in argcomplete

To help you get started, we’ve selected a few argcomplete examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github codalab / codalab-worksheets / codalab / lib / bundle_cli.py View on Github external
def complete_command(self, command):
        """
        Given a command string, return a list of suggestions to complete the last token.
        """
        parser = Commands.build_parser(self)
        cf = argcomplete.CompletionFinder(parser)
        cword_prequote, cword_prefix, _, comp_words, first_colon_pos = argcomplete.split_line(command, len(command))

        # Strip whitespace and parse according to shell escaping rules
        try:
            clean = lambda s: shlex.split(s.strip())[0] if s else ''
        except ValueError as e:
            raise UsageError(e.message)
        return map(clean, cf._get_completions(comp_words, cword_prefix, cword_prequote, first_colon_pos))
github joowani / dtags / dtags / completion.py View on Github external
"""All the things related to auto-completion."""

from argcomplete import CompletionFinder


class DTagsCompletionFinder(CompletionFinder):
    """Completion finder for DTags."""

    def _get_option_completions(self, parser, cword_prefix):
        """Skip auto-completion for optional arguments."""
        return []


class ChoicesCompleter(object):
    """Completer initialized with a set of all possible choices."""

    def __init__(self, choices=None):
        self.choices = map(str, choices) if choices else []

    def __call__(self, prefix, **kwargs):
        return (c for c in self.choices if c.startswith(prefix))
github wapiflapi / gxf / gxf / commands.py View on Github external
self.prefix = prefix

        # Setup a parser for this command.
        self.parser = ArgumentParser(
            prog=self.cmdname,
            description=self.__doc__)
        self.setup(self.parser)

        # We need to set the .completer hints in order for
        # argcomplete to know what to do on types we known.
        for action in self.parser._actions:
            if hasattr(action.type, "argcompleter"):
                action.completer = action.type.argcompleter

        # And prepare everything for autocompletion.
        self.completer = argcomplete.CompletionFinder(
            self.parser, always_complete_options=True)

        # gdb generates its help from the docstring.
        # We temporarilly overwrite it with argparse's output.
        old_doc, self.__doc__ = self.__doc__, self.parser.format_help().strip()

        # Call gdb's init. This will cause the command to be registerd.
        super().__init__(cmdname, cmdtype, prefix=prefix)

        # Restore the docstring so that it is usefull when looking
        # up help in python or when used for any other puprpose.
        self.__doc__ = old_doc
github Samsung / veles / veles / cmdline.py View on Github external
"(pass \"-\" to make it _config.py, "
                           "pass empty to ignore)."
        ).pretty_name = "configuration file"
        arg = parser.add_argument(
            'config_list',
            help="Configuration overrides separated by a whitespace, for "
                 "example: \nroot.global_alpha=0.006\n "
                 "root.snapshot_prefix='test_pr'", nargs='*',
            metavar="key=value")
        arg.pretty_name = "override configuration"
        arg.important = True
        parser.add_argument("-b", "--background", default=False,
                            help="Run in background as a daemon.",
                            action='store_true')
        try:
            class NoEscapeCompleter(argcomplete.CompletionFinder):
                def quote_completions(self, completions, *args, **kwargs):
                    return completions

            NoEscapeCompleter()(parser)  # pylint: disable=E1102
        except:
            pass
        return parser
github Azure / azure-cli-shell / azclishell / argfinder.py View on Github external
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import argparse
import os
import sys

from argcomplete import CompletionFinder
from argcomplete.compat import USING_PYTHON2, ensure_bytes


class ArgsFinder(CompletionFinder):
    """ gets the parsed args """

    def get_parsed_args(self, comp_words):
        """ gets the parsed args from a patched parser """
        active_parsers = self._patch_argument_parser()

        parsed_args = argparse.Namespace()

        self.completing = True
        if USING_PYTHON2:
            # Python 2 argparse only properly works with byte strings.
            comp_words = [ensure_bytes(word) for word in comp_words]

        try:
            stderr = sys.stderr
            sys.stderr = os.open(os.devnull, "w")
github ralphje / imagemounter / imagemounter / cli / shell.py View on Github external
for name in self.get_names():
            if name.startswith('parser_'):
                parser = subparsers.add_parser(name[7:])
                parser.set_defaults(func=getattr(self, 'arg_' + name[7:]))
                getattr(self, name)(parser)

        self.argparser_completer = None

        try:
            import argcomplete
        except ImportError:
            pass
        else:
            os.environ.setdefault("_ARGCOMPLETE_COMP_WORDBREAKS", " \t\"'")
            self.argparser_completer = argcomplete.CompletionFinder(self.argparser)
github alttch / icli / icli / __init__.py View on Github external
def save_history():
            if self.interactive_history_file:
                try:
                    readline.write_history_file(
                        os.path.expanduser(self.interactive_history_file))
                except:
                    pass

        if stream:
            input_strings = stream.readlines()
            if not input_strings:
                return
            sidx = 0
        else:
            self._i_completer = argcomplete.CompletionFinder(
                self,
                default_completer=argcomplete.completers.SuppressCompleter())
            readline.set_completer_delims('')
            readline.set_completer(self.interactive_completer)
            readline.parse_and_bind('tab: complete')
            readline.set_history_length(self.interactive_history_length)
            if self.interactive_history_file:
                try:
                    readline.read_history_file(
                        os.path.expanduser(self.interactive_history_file))
                except:
                    pass
        while True:
            try:
                if stream:
                    try:
github Azure / azure-cli / src / command_modules / azure-cli-interactive / azure / cli / command_modules / interactive / azclishell / argfinder.py View on Github external
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import argparse

from argcomplete import CompletionFinder
from argcomplete.compat import USING_PYTHON2, ensure_bytes


class ArgsFinder(CompletionFinder):
    """ gets the parsed args """
    def __init__(self, parser, outstream=None):
        super(ArgsFinder, self).__init__(parser)
        self.outstream = outstream

    def get_parsed_args(self, comp_words):
        """ gets the parsed args from a patched parser """
        active_parsers = self._patch_argument_parser()

        parsed_args = argparse.Namespace()

        self.completing = True
        if USING_PYTHON2:
            # Python 2 argparse only properly works with byte strings.
            comp_words = [ensure_bytes(word) for word in comp_words]