Python rlcompleter.Completer() Examples

The following are 30 code examples of rlcompleter.Completer(). 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 rlcompleter , or try the search function .
Example #1
Source File: pundle.py    From pundler with BSD 2-Clause "Simplified" License 9 votes vote down vote up
def run_console(glob):
    import readline
    import rlcompleter
    import atexit
    import code

    history_path = os.path.expanduser("~/.python_history")

    def save_history(history_path=history_path):
        readline.write_history_file(history_path)
    if os.path.exists(history_path):
        readline.read_history_file(history_path)

    atexit.register(save_history)

    readline.set_completer(rlcompleter.Completer(glob).complete)
    readline.parse_and_bind("tab: complete")
    code.InteractiveConsole(locals=glob).interact() 
Example #2
Source File: test_rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_duplicate_globals(self):
        namespace = {
            'False': None,  # Keyword vs builtin vs namespace
            'assert': None,  # Keyword vs namespace
            'try': lambda: None,  # Keyword vs callable
            'memoryview': None,  # Callable builtin vs non-callable
            'Ellipsis': lambda: None,  # Non-callable builtin vs callable
        }
        completer = rlcompleter.Completer(namespace)
        self.assertEqual(completer.complete('False', 0), 'False')
        self.assertIsNone(completer.complete('False', 1))  # No duplicates
        self.assertEqual(completer.complete('assert', 0), 'assert')
        self.assertIsNone(completer.complete('assert', 1))
        self.assertEqual(completer.complete('try', 0), 'try')
        self.assertIsNone(completer.complete('try', 1))
        # No opening bracket "(" because we overrode the built-in class
        self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
        self.assertIsNone(completer.complete('memoryview', 1))
        self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
        self.assertIsNone(completer.complete('Ellipsis', 1)) 
Example #3
Source File: complete_namespace.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def complete_names(word, namespace):
    """Complete variable names or attributes

    :param word: word to be completed
    :type word: str
    :param namespace: namespace
    :type namespace: dict
    :returns: completion matches
    :rtype: list of str

    >>> complete_names('fo', {'foo': 'bar'})
    ['foo', 'for', 'format(']
    """
    # start completer
    completer = rlcompleter.Completer(namespace)
    # find matches with std library (don't try to implement this yourself)
    completer.complete(word, 0)
    return sorted(set(completer.matches)) 
Example #4
Source File: shell.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def enable_autocomplete_and_history(adir,env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("bind ^I rl_complete"
                                if sys.platform == 'darwin'
                                else "tab: complete")
        history_file = os.path.join(adir,'.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete) 
Example #5
Source File: konch.py    From konch with MIT License 6 votes vote down vote up
def start(self) -> None:
        try:
            import readline
        except ImportError:
            pass
        else:
            # We don't have to wrap the following import in a 'try', because
            # we already know 'readline' was imported successfully.
            import rlcompleter

            readline.set_completer(rlcompleter.Completer(self.context).complete)
            readline.parse_and_bind("tab:complete")

        if self.prompt:
            sys.ps1 = self.prompt
        if self.output:
            warnings.warn("Custom output templates not supported by PythonShell.")
        code.interact(self.banner, local=self.context)
        return None 
Example #6
Source File: test_rlcompleter.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_main():
    support.run_unittest(TestRlcompleter)

    def test_duplicate_globals(self):
        namespace = {
            'False': None,  # Keyword vs builtin vs namespace
            'assert': None,  # Keyword vs namespace
            'try': lambda: None,  # Keyword vs callable
            'memoryview': None,  # Callable builtin vs non-callable
            'Ellipsis': lambda: None,  # Non-callable builtin vs callable
        }
        completer = rlcompleter.Completer(namespace)
        self.assertEqual(completer.complete('False', 0), 'False')
        self.assertIsNone(completer.complete('False', 1))  # No duplicates
        self.assertEqual(completer.complete('assert', 0), 'assert')
        self.assertIsNone(completer.complete('assert', 1))
        self.assertEqual(completer.complete('try', 0), 'try')
        self.assertIsNone(completer.complete('try', 1))
        # No opening bracket "(" because we overrode the built-in class
        self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
        self.assertIsNone(completer.complete('memoryview', 1))
        self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
        self.assertIsNone(completer.complete('Ellipsis', 1)) 
Example #7
Source File: test_rlcompleter.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_duplicate_globals(self):
        namespace = {
            'False': None,  # Keyword vs builtin vs namespace
            'assert': None,  # Keyword vs namespace
            'try': lambda: None,  # Keyword vs callable
            'memoryview': None,  # Callable builtin vs non-callable
            'Ellipsis': lambda: None,  # Non-callable builtin vs callable
        }
        completer = rlcompleter.Completer(namespace)
        self.assertEqual(completer.complete('False', 0), 'False')
        self.assertIsNone(completer.complete('False', 1))  # No duplicates
        self.assertEqual(completer.complete('assert', 0), 'assert')
        self.assertIsNone(completer.complete('assert', 1))
        self.assertEqual(completer.complete('try', 0), 'try')
        self.assertIsNone(completer.complete('try', 1))
        # No opening bracket "(" because we overrode the built-in class
        self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
        self.assertIsNone(completer.complete('memoryview', 1))
        self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
        self.assertIsNone(completer.complete('Ellipsis', 1)) 
Example #8
Source File: client.py    From telenium with MIT License 6 votes vote down vote up
def run_client(host="localhost", port=9901):
    import code
    import readline
    import rlcompleter
    url = "http://{host}:{port}/jsonrpc".format(host=host, port=port)
    cli = TeleniumHttpClient(url=url, timeout=5)

    print("Connecting to {}".format(url))
    while not cli.ping():
        sleep(.1)
    print("Connected!")

    vars = globals()
    vars.update(locals())
    readline.set_completer(rlcompleter.Completer(vars).complete)
    readline.parse_and_bind("tab: complete")
    shell = code.InteractiveConsole(vars)
    shell.interact() 
Example #9
Source File: readline.py    From daudin with MIT License 6 votes vote down vote up
def complete(self, text, state):
        if state == 0:
            self.completions = []
            append = self.completions.append
            for path in glob.glob(text + '*'):
                if os.path.isdir(path):
                    if not path.endswith(os.sep):
                        path += os.sep
                else:
                    path += ' '
                append(path)

            pycompleter = rlcompleter.Completer(namespace=self.local).complete
            for i in count():
                completion = pycompleter(text, i)
                if completion is None:
                    break
                else:
                    append(completion)

        try:
            return self.completions[state]
        except IndexError:
            return None 
Example #10
Source File: modified_ROOT_v6.02.05.py    From pax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def global_matches( self, text ):
         matches = rlcompleter.Completer.global_matches( self, text )
         if not matches: matches = []
         matches += self.file_matches( text )
         return matches 
Example #11
Source File: modified_ROOT_v5.34.25.py    From pax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def attr_matches( self, text ):
         matches = rlcompleter.Completer.attr_matches( self, text )
         if not matches: matches = []
         b = text.find('.')
         try:
            if 0 <= b and self.namespace[text[:b]].__name__ == 'ROOT':
               matches += self.root_global_matches( text[b+1:], text[:b+1] )
         except AttributeError:    # not all objects have a __name__
            pass
         return matches 
Example #12
Source File: modified_ROOT_v5.34.25.py    From pax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def global_matches( self, text ):
         matches = rlcompleter.Completer.global_matches( self, text )
         if not matches: matches = []
         matches += self.file_matches( text )
         return matches 
Example #13
Source File: modified_ROOT_v6.02.05.py    From pax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def attr_matches( self, text ):
         matches = rlcompleter.Completer.attr_matches( self, text )
         if not matches: matches = []
         b = text.find('.')
         try:
            if 0 <= b and self.namespace[text[:b]].__name__ == 'ROOT':
               matches += self.root_global_matches( text[b+1:], text[:b+1] )
         except AttributeError:    # not all objects have a __name__
            pass
         return matches 
Example #14
Source File: test_rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.stdcompleter = rlcompleter.Completer()
        self.completer = rlcompleter.Completer(dict(spam=int,
                                                    egg=str,
                                                    CompleteMe=CompleteMe))

        # forces stdcompleter to bind builtins namespace
        self.stdcompleter.complete('', 0) 
Example #15
Source File: test_rlcompleter.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_namespace(self):
        class A(dict):
            pass
        class B(list):
            pass

        self.assertTrue(self.stdcompleter.use_main_ns)
        self.assertFalse(self.completer.use_main_ns)
        self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
        self.assertRaises(TypeError, rlcompleter.Completer, B((1,))) 
Example #16
Source File: test_rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_namespace(self):
        class A(dict):
            pass
        class B(list):
            pass

        self.assertTrue(self.stdcompleter.use_main_ns)
        self.assertFalse(self.completer.use_main_ns)
        self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
        self.assertRaises(TypeError, rlcompleter.Completer, B((1,))) 
Example #17
Source File: test_rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_excessive_getattr(self):
        # Ensure getattr() is invoked no more than once per attribute
        class Foo:
            calls = 0
            @property
            def bar(self):
                self.calls += 1
                return None
        f = Foo()
        completer = rlcompleter.Completer(dict(f=f))
        self.assertEqual(completer.complete('f.b', 0), 'f.bar')
        self.assertEqual(f.calls, 1) 
Example #18
Source File: test_rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_complete(self):
        completer = rlcompleter.Completer()
        self.assertEqual(completer.complete('', 0), '\t')
        self.assertEqual(completer.complete('a', 0), 'and')
        self.assertEqual(completer.complete('a', 1), 'as')
        self.assertEqual(completer.complete('as', 2), 'assert')
        self.assertEqual(completer.complete('an', 0), 'and') 
Example #19
Source File: completer.py    From sos-notebook with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_completions(self, line):
        text = last_valid(line)

        completer = rlcompleter.Completer(env.sos_dict._dict)
        return text, completer.global_matches(text) 
Example #20
Source File: test_emacs.py    From malkit with MIT License 5 votes vote down vote up
def test_complete (self):
        import rlcompleter
        logger.sock_silent = False

        log("-" * 50)
        r = EmacsModeTest()
        completerobj = rlcompleter.Completer()
        def _nop(val, word):
            return word
        completerobj._callable_postfix = _nop
        r.completer = completerobj.complete
        r._bind_key("tab", r.complete)
        r.input('"exi(ksdjksjd)"')
        r.input('Control-a')
        r.input('Right')
        r.input('Right')
        r.input('Right')
        r.input('Tab')
        self.assert_line(r, "exit(ksdjksjd)", 4)

        r.input('Escape')
        r.input('"exi"')
        r.input('Control-a')
        r.input('Right')
        r.input('Right')
        r.input('Right')
        r.input('Tab')
        self.assert_line(r, "exit", 4) 
Example #21
Source File: ballisticacore_server.py    From ballistica with MIT License 5 votes vote down vote up
def _enable_tab_completion(self, locs: Dict) -> None:
        """Enable tab-completion on platforms where available (linux/mac)."""
        try:
            import readline
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(locs).complete)
            readline.parse_and_bind('tab:complete')
        except ImportError:
            # This is expected (readline doesn't exist under windows).
            pass 
Example #22
Source File: ConsoleDialog.py    From nionswift with GNU General Public License v3.0 5 votes vote down vote up
def complete_command(self, command: str) -> typing.Tuple[str, typing.List[str]]:
        terms = list()
        completed_command = command
        completer = rlcompleter.Completer(namespace=self.__console.locals)
        index = 0
        rx = "([" + re.escape(ConsoleWidgetStateController.delims) + "])"
        # the parenthesis around rx make it a group. This will cause split to keep the characters in rx in the
        # list, so that we can reconstruct the original string later
        split_commands = re.split(rx, command)
        if len(split_commands) > 0:
            completion_term = split_commands[-1]
            while True:
                term = completer.complete(completion_term, index)
                if term is None:
                    break
                index += 1
                # for some reason rlcomplete returns "\t" when completing "", so exclude that case here
                if not term.startswith(completion_term + "__") and term != "\t":
                    terms.append(term)
            if len(terms) == 1:
                completed_command = command[:command.rfind(completion_term)] + terms[0]
                terms = list()
            elif len(terms) > 1:
                common_prefix = ConsoleWidgetStateController.get_common_prefix(terms)
                completed_command = "".join(split_commands[:-1]) + common_prefix

        return completed_command, terms 
Example #23
Source File: test_rlcompleter.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.stdcompleter = rlcompleter.Completer()
        self.completer = rlcompleter.Completer(dict(spam=int,
                                                    egg=str,
                                                    CompleteMe=CompleteMe))

        # forces stdcompleter to bind builtins namespace
        self.stdcompleter.complete('', 0) 
Example #24
Source File: test_rlcompleter.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_namespace(self):
        class A(dict):
            pass
        class B(list):
            pass

        self.assertTrue(self.stdcompleter.use_main_ns)
        self.assertFalse(self.completer.use_main_ns)
        self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
        self.assertRaises(TypeError, rlcompleter.Completer, B((1,))) 
Example #25
Source File: test_emacs.py    From OWASP-ZSC with GNU General Public License v3.0 5 votes vote down vote up
def test_complete(self):
        import rlcompleter
        logger.sock_silent = False

        log("-" * 50)
        r = EmacsModeTest()
        completerobj = rlcompleter.Completer()

        def _nop(val, word):
            return word

        completerobj._callable_postfix = _nop
        r.completer = completerobj.complete
        r._bind_key("tab", r.complete)
        r.input('"exi(ksdjksjd)"')
        r.input('Control-a')
        r.input('Right')
        r.input('Right')
        r.input('Right')
        r.input('Tab')
        self.assert_line(r, "exit(ksdjksjd)", 4)

        r.input('Escape')
        r.input('"exi"')
        r.input('Control-a')
        r.input('Right')
        r.input('Right')
        r.input('Right')
        r.input('Tab')
        self.assert_line(r, "exit", 4) 
Example #26
Source File: test_rlcompleter.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        self.stdcompleter = rlcompleter.Completer()
        self.completer = rlcompleter.Completer(dict(spam=int,
                                                    egg=str,
                                                    CompleteMe=CompleteMe))

        # forces stdcompleter to bind builtins namespace
        self.stdcompleter.complete('', 0) 
Example #27
Source File: test_rlcompleter.py    From android_universal with MIT License 5 votes vote down vote up
def test_namespace(self):
        class A(dict):
            pass
        class B(list):
            pass

        self.assertTrue(self.stdcompleter.use_main_ns)
        self.assertFalse(self.completer.use_main_ns)
        self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
        self.assertRaises(TypeError, rlcompleter.Completer, B((1,))) 
Example #28
Source File: test_rlcompleter.py    From android_universal with MIT License 5 votes vote down vote up
def test_excessive_getattr(self):
        # Ensure getattr() is invoked no more than once per attribute
        class Foo:
            calls = 0
            @property
            def bar(self):
                self.calls += 1
                return None
        f = Foo()
        completer = rlcompleter.Completer(dict(f=f))
        self.assertEqual(completer.complete('f.b', 0), 'f.bar')
        self.assertEqual(f.calls, 1) 
Example #29
Source File: test_rlcompleter.py    From android_universal with MIT License 5 votes vote down vote up
def test_uncreated_attr(self):
        # Attributes like properties and slots should be completed even when
        # they haven't been created on an instance
        class Foo:
            __slots__ = ("bar",)
        completer = rlcompleter.Completer(dict(f=Foo()))
        self.assertEqual(completer.complete('f.', 0), 'f.bar') 
Example #30
Source File: test_rlcompleter.py    From android_universal with MIT License 5 votes vote down vote up
def test_complete(self):
        completer = rlcompleter.Completer()
        self.assertEqual(completer.complete('', 0), '\t')
        self.assertEqual(completer.complete('a', 0), 'and ')
        self.assertEqual(completer.complete('a', 1), 'as ')
        self.assertEqual(completer.complete('as', 2), 'assert ')
        self.assertEqual(completer.complete('an', 0), 'and ')
        self.assertEqual(completer.complete('pa', 0), 'pass')
        self.assertEqual(completer.complete('Fa', 0), 'False')
        self.assertEqual(completer.complete('el', 0), 'elif ')
        self.assertEqual(completer.complete('el', 1), 'else')
        self.assertEqual(completer.complete('tr', 0), 'try:')