我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用rlcompleter.Completer()。
def interactive(self): utils.set_prompt(ps1="(rudra) ", ps2="... ") import os import readline import rlcompleter import atexit histfile = os.path.join(os.environ["HOME"], ".rudrahistory") if os.path.isfile(histfile): readline.read_history_file(histfile) atexit.register(readline.write_history_file, histfile) r = self print "Use the \"r\" object to analyze files" vars = globals() vars.update(locals()) readline.set_completer(rlcompleter.Completer(vars).complete) readline.parse_and_bind("tab: complete") del os, histfile, readline, rlcompleter, atexit code.interact(banner="", local=vars)
def enable_autocomplete_and_history(adir, env): try: import rlcompleter import atexit import readline except ImportError: pass else: readline.parse_and_bind("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)
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))
def test_complete (self): import rlcompleter logger.sock_silent=False log_sock("-"*50,"debug") r=EmacsModeTest() r.completer=rlcompleter.Completer().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)
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))
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))
def complete(self, text, state): """ Derived from rlcompleter.Completer.complete() """ if self.use_main_ns: self.namespace = __main__.__dict__ if text == "": self.help() return None if state == 0: if "." in text: self.matches = self.attr_matches(text) else: self.matches = self.global_matches(text) try: return self.matches[state] except IndexError: return None
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)
def handle(self, **options): try: if options['plain']: # Don't bother loading IPython, because the user wants plain Python. raise ImportError self.run_shell(shell=options['interface']) except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. imported_objects = {} try: # Try activating rlcompleter, because it's handy. 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(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'): if not pythonrc: continue pythonrc = os.path.expanduser(pythonrc) if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. 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(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. Mac OSX). # These lines are copied from Lib/site.py on Python 3.4. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'): if not pythonrc: continue pythonrc = os.path.expanduser(pythonrc) if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. 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(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. macOS). # These lines are copied from Lib/site.py on Python 3.4. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]): if not pythonrc: continue if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def improved_rlcompleter(self): """Enhances the default rlcompleter The function enhances the default rlcompleter by also doing pathname completion and module name completion for import statements. Additionally, it inserts a tab instead of attempting completion if there is no preceding text. """ completer = rlcompleter.Completer(namespace=self.locals) # - remove / from the delimiters to help identify possibility for path completion readline.set_completer_delims(readline.get_completer_delims().replace('/', '')) modlist = frozenset(name for _, name, _ in pkgutil.iter_modules()) def complete_wrapper(text, state): line = readline.get_line_buffer().strip() if line == '': return None if state > 0 else self.tab if state == 0: if line.startswith(('import', 'from')): completer.matches = [name for name in modlist if name.startswith(text)] else: match = completer.complete(text, state) if match is None and '/' in text: completer.matches = glob.glob(text+'*') try: match = completer.matches[state] return '{}{}'.format(match, ' ' if keyword.iskeyword(match) else '') except IndexError: return None return complete_wrapper
def handle(self, *args, **options): use_plain = options.get('plain', False) show_imports = options.get('show_imports', True) imported_objects = self.import_objects(show_imports) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError from IPython import start_ipython except ImportError: # Plain import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. try: # Try activating rlcompleter, because it's handy. 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(imported_objects).complete) readline.parse_and_bind("tab:complete") code.interact(banner='', local=imported_objects) else: # IPython start_ipython(argv=['--no-banner', '--no-confirm-exit'], user_ns=imported_objects)
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)
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,)))
def main(): banner = "PyMal - Python Interactive Shell for Malware Analysis.\nUse Object \"pm\" to access the malware analysis related functions!\nAuthor: Amit Malik\nhttp://www.securityxploded.com\n" pm = PyMal() class pymalcomplete(rlcompleter.Completer): # Code segment from scapy - It is neat and mature def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) try: object = eval(expr) except: object = eval(expr, session) words = dir(object) if hasattr(pm,"__class__" ): words = words + rlcompleter.get_class_members(pm.__class__) matches = [] n = len(attr) for word in words: if word[:n] == attr: matches.append("%s.%s" % (expr, word)) return matches readline.set_completer(pymalcomplete().complete) readline.parse_and_bind("C-o: operate-and-get-next") readline.parse_and_bind('tab: complete') code.interact(banner=banner,local = locals())
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)
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)
def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. 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(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. Mac OSX). # These lines are copied from Lib/site.py on Python 3.4. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]): if not pythonrc: continue if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def shell(ipython): """Runs a Python shell with QPD context""" import code import readline import rlcompleter banner_msg = ( "Welcome to QPD interactive shell\n" "\tAuto imported: app, db, models, views, admin" ) _vars = globals() _vars.update(locals()) _vars.update(dict(app=app, db=db, models=models, views=views, admin=admin)) readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind("tab: complete") try: if ipython is True: from IPython import start_ipython from traitlets.config import Config c = Config() c.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=c) else: raise ImportError except ImportError: shell = code.InteractiveConsole(_vars) shell.interact(banner=banner_msg)
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')
def attr_matches(self, text): """ Derived from rlcompleter.Completer.attr_matches() """ m = self.PATTERN.match(text) if not m: return [] expr, attr = m.group(1, 3) try: thisobject = eval(expr, self.namespace) except Exception: return [] # get the content of the object, except __builtins__ words = dir(thisobject) if "__builtins__" in words: words.remove("__builtins__") if hasattr(thisobject, '__class__'): words.append('__class__') words.extend(rlcompleter.get_class_members(thisobject.__class__)) matches = [] n = len(attr) for word in words: if attr == '' and word[0] == '_': continue if word[:n] == attr and hasattr(thisobject, word): val = getattr(thisobject, word) word = self._callable_postfix(val, "%s.%s" % (expr, word)) matches.append(word) return matches