def complete(text, namespace=None): """Complete TEXT in NAMESPACE and print a Lisp list of completions. NAMESPACE is currently not used.""" if namespace is None: namespace = __main__.__dict__ c = rlcompleter.Completer(namespace) try: if '.' in text: matches = c.attr_matches(text) else: matches = c.global_matches(text) print '_emacs_out (', for elt in matches: print '"%s"' % elt, print ')' except: print '_emacs_out ()'
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 run_classic_shell(locals, globals, first_time): if first_time: banner = "Hit Ctrl-D to return to PuDB." else: banner = "" ns = SetPropagatingDict([locals, globals], locals) if HAVE_READLINE: readline.set_completer( rlcompleter.Completer(ns).complete) from code import InteractiveConsole cons = InteractiveConsole(ns) cons.interact(banner)
def complete(self, text, state): """ Return the next possible completion for text, using the current frame's local namespace. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Reference: https://code.activestate.com/recipes/498182/ """ # Attached a completer class and make sure it uses the current local scope if not hasattr(self, 'completer'): self.completer = rlcompleter.Completer(self.curframe.f_locals) else: self.completer.namespace = self.curframe.f_locals return self.completer.complete(text, state)
def prompt(self, old: Any, new: Any) -> Tuple[str, str]: review_env = ReviewEnvironment(old=old, new=new) try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(review_env).complete) readline.parse_and_bind("tab: complete") except ImportError: pass console = ReviewConsole(review_env) console.interact("\na: accept, r: reject, s: skip", "") return review_env.outcome or ("s", "skipping snapshot")
def complete(self, statement, session): """Autocomplete the statement in the session's globals.""" statement_module = new.module('__main__') import __builtin__ statement_module.__builtin__ = __builtin__ old_main = sys.modules.get('__main__') try: sys.modules['__main__'] = statement_module statement_module.__name__ = '__main__' # re-evaluate the unpicklables for code in session.unpicklables: exec code in statement_module.__dict__ old_globals = dict(statement_module.__dict__) # re-initialize the globals session_globals_dict = session.globals_dict() for name, val in session_globals_dict.items(): try: statement_module.__dict__[name] = val except: session.remove_global(name) __builtin__._ = session_globals_dict.get('_') completer = rlcompleter.Completer(statement_module.__dict__) if '=' in statement: statement = statement.split('=', 1)[1].strip() # XXX need a better way to do this if '.' in statement: return completer.attr_matches(statement) else: return completer.global_matches(statement) finally: sys.modules['__main__'] = old_main try: del __builtin__._ except AttributeError: pass
def handle(self, *args, **options): # 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") # Get $PYTHONSTARTUP and then .pythonrc.py 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 c_all = cont.Contact.objects_no_link.all() m_all = cont.Message.objects.all() v_all = cont.Visit.objects.all() s_all = cont.StatusChange.objects.all() namespace = globals() namespace.update(locals()) if options['test'] is True: namespace.update(test_handler(namespace)) code.interact(local=namespace)
def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from django.db.models.loading import get_models loaded_models = get_models() use_plain = options.get('plain', False) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError import IPython # Explicitly pass an empty list as arguments, because otherwise IPython # would use sys.argv from this script. shell = IPython.Shell.IPShell(argv=[]) shell.mainloop() 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 import user. if not use_plain: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
def get_plain(self, options): # Using normal Python shell import code imported_objects = self.get_imported_objects(options) 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") use_pythonrc = options['use_pythonrc'] no_startup = options['no_startup'] # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if use_pythonrc or not 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 with open(pythonrc) as handle: pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. try: exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects) except Exception: traceback.print_exc() if self.tests_mode: raise def run_plain(): code.interact(local=imported_objects) return run_plain
def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.cut_buffer = '' self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.rl_history = History(duplicates=config.hist_duplicates) self.s_hist = [] self.history = [] self.evaluating = False # Use the interpreter's namespace only for the readline stuff: self.completer = rlcompleter.Completer(self.interp.locals) self.completer.attr_matches = self.attr_matches # Gna, Py 2.6's rlcompleter searches for __call__ inside the # instance instead of the type, so we monkeypatch to prevent # side-effects (__getattr__/__getattribute__) self.completer._callable_postfix = self._callable_postfix self.matches = [] self.matches_iter = MatchesIterator() self.argspec = None self.current_func = None self.highlighted_paren = None self.list_win_visible = False self._C = {} self.prev_block_finished = 0 self.interact = Interaction(self.config) self.ps1 = '>>> ' self.ps2 = '... ' # previous pastebin content to prevent duplicate pastes, filled on call # to repl.pastebin self.prev_pastebin_content = '' self.prev_pastebin_url = '' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): self.rl_history.load(pythonhist, getpreferredencoding() or "ascii")
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 Python's Lib/site.py. 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 with open(pythonrc) as handle: pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. try: exec(compile(pythonrc_code, pythonrc, "exec"), imported_objects) except Exception: traceback.print_exc() code.interact(local=imported_objects)
def run_shell(self, opts): """\nDebug method to run a shell""" import code import readline import rlcompleter opts['remotes'] = self.get_remotes(opts) data = { 'self': self, 'gitlab': glapi, 'opts': opts, } readline.set_completer(rlcompleter.Completer(data).complete) readline.parse_and_bind("tab: complete") shl = code.InteractiveConsole(data) shl.interact() sys.exit(1)
def handle_noargs(self, **options): use_plain = options.get('plain', False) no_startup = options.get('no_startup', False) interface = options.get('interface', None) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError self.run_shell(shell=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 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 debug(self): """ Use an interactive mode to debug the program. """ import code sys.ps1 = "[cc] >>> " vars = globals() vars.update(locals()) if hasattr( self, 'subshell', ): vars.update(**self.subshell) import readline, rlcompleter readline.set_completer(rlcompleter.Completer(vars).complete) readline.parse_and_bind("tab: complete") code.interact(local=vars, banner='')
def copen(filename=None, interactive='True'): """Opens interactive console and execute the content of filename""" context = globals().copy() readline.set_completer(rlcompleter.Completer(context).complete) readline.parse_and_bind("tab: complete") shell = code.InteractiveConsole(context) if filename: with open(filename) as f: cmds = f.read() shell.runcode(START.format(path=os.path.dirname(filename))) shell.runcode(cmds) if interactive == 'True': shell.interact(banner='') else: txt = 'Press return to close window' print(f'\n{"-" * len(txt)}\n{txt}') input('')
def __init__(self, *args, run_callback=None, **kwargs): super().__init__(*args, **kwargs) if readline is not None: self._histfile = os.path.expanduser("~/.glasgow-history") try: readline.read_history_file(self._histfile) except FileNotFoundError: pass completer = rlcompleter.Completer(self.locals) readline.parse_and_bind("tab: complete") readline.set_completer(completer.complete) self.locals["__name__"] = __name__.split(".")[0] self.run_callback = run_callback self._future = None
def interact(driver): try: import code vars = globals() vars.update(locals()) if os.name != 'nt': import readline import rlcompleter readline.set_completer(rlcompleter.Completer(vars).complete) readline.parse_and_bind("tab: complete") shell = code.InteractiveConsole(vars) shell.interact() except: print("[-] Error with python repl!") finally: print("[+] Done with python repl") driver.quit()
def repl(local, histfile=None, banner=None): import readline import rlcompleter if 'libedit' in readline.__doc__: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') if histfile is not None and os.path.exists(histfile): # avoid duplicate reading if readline.get_current_history_length() <= 0: readline.set_history_length(10000) readline.read_history_file(histfile) import code readline.set_completer(rlcompleter.Completer(local).complete) code.interact(local=local, banner=banner) if histfile is not None: readline.write_history_file(histfile)
def __init__(self, locals=None, histfile=None, writefunc=None): code.InteractiveConsole.__init__(self, locals) self.thread = None self._exit = False if writefunc and callable(writefunc): self.write = writefunc try: import readline except ImportError: pass else: try: import rlcompleter readline.set_completer(rlcompleter.Completer(locals).complete) except ImportError: pass readline.parse_and_bind("tab: complete")
def __init__(self, locals=None, filename="<console>", histfile=os.path.expanduser("~/.console-history")): code.InteractiveConsole.__init__(self, locals, filename) try: import readline except ImportError: pass else: try: import rlcompleter readline.set_completer(rlcompleter.Completer(locals).complete) except ImportError: pass readline.parse_and_bind("tab: complete") self.init_history(histfile)
def run_debug_console(simulation, show_banner=True): """ Run a debug console with some useful variables available """ banner = ['Ocellaris interactive console\n'] # Everything from dolfin should be available import dolfin debug_locals = dict(**dolfin.__dict__) # All variables in the data dict should be available debug_locals.update(simulation.data) # The simulation object shoule be available debug_locals['simulation'] = simulation # Create a banner to show before the console banner.append('Available variables:') names = list(simulation.data.keys()) + ['simulation'] for i, name in enumerate(sorted(names)): if i % 4 == 0: banner[-1] += '\n' banner[-1] += ' %-18s' % name banner.append( '\n\nPress Ctrl+D to continue running the simulation.' '\nRunning exit() or quit() will stop Ocellaris.' ) # Add some convenience functions funcs, info = define_convenience_functions(simulation) debug_locals.update(funcs) banner.extend(info) # Setup tab completion readline.set_completer(rlcompleter.Completer(debug_locals).complete) readline.parse_and_bind("tab: complete") if not show_banner: banner = [] print('=== OCELLARIS CONSOLE === ' * 3) banner.append('\n>>> from dolfin import *') code.interact('\n'.join(banner), local=debug_locals) print('= OCELLARIS CONSOLE ====' * 3)
def main(): args = parse_args() global_vars = {} if args.main: global_vars['__name__'] = "__main__" for script_filename in args.FILE: if args.verbose: print("loading file '{}'".format(script_filename)) with open(script_filename) as fin: func = compile(fin.read(), script_filename, 'exec') exec(func, global_vars) if args.verbose and args.FILE: print() if args.command is not None: for command in args.command: if args.verbose: print("executing: '{}'".format(command)) func = compile(command, "command", 'exec') exec(func, global_vars) if args.verbose and args.command: print() readline.set_completer(rlcompleter.Completer(global_vars).complete) readline.parse_and_bind("tab: complete") if args.verbose: for k, v in global_vars.items(): if k != "__builtins__": print("{} = {}".format(k, v)) print() if not args.quit: history_file = os.path.expanduser("~/.ipy_history") if os.path.exists(history_file): readline.read_history_file(history_file) code.interact(banner="", local=global_vars) readline.write_history_file(history_file)
def get_plain(self, options): # Using normal Python shell import code imported_objects = self.get_imported_objects(options) 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") use_pythonrc = options.get('use_pythonrc', False) no_startup = options.get('no_startup', False) # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if use_pythonrc or not 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 with open(pythonrc) as handle: pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. try: exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects) except Exception: traceback.print_exc() def run_plain(): code.interact(local=imported_objects) return run_plain
def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from django.apps import apps loaded_models = apps.get_models() 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 = { 'datetime': datetime, 'cache': cache, 'reverse': reverse, 'resolve': resolve, 'settings': settings, } # Put all of the models into the local namespace. for model in loaded_models: imported_objects[model.__name__] = model 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 import user. pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
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 readline_setup(exports): """setup readline completion, if available. :param exports: the namespace to be used for completion :return: True on success """ try: import readline except ImportError: # no completion for you. readline = None return False else: import rlcompleter readline.set_completer( rlcompleter.Completer(namespace=exports).complete) return True
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()
def enableAutocomplete(ns=None): """ Enables tab-based autocomplete. The readline module must be available. <ns> is the namespace which readline starts out with. This should generally be the same as your interpreter uses, but defaults to globals() if ns is not provided. If you need to change the namespace at a later point, simply set the completer manually with: import readline, rlcompleter readline.set_completer(rlcompleter.Completer(ns).complete) """ if ns is None: ns = globals() if readline: readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") else: print "readline module not available. Must be installed for tab-based autocomplete to work. Google it."
def rpc_get_completions(self, project_root, filename, source, offset): """Get completions for symbol at the offset. Wrapper around rlcompleter. """ completer = rlcompleter.Completer() symbol, start, end = find_dotted_symbol_backward(source, offset) completions = [] i = 0 while True: res = completer.complete(symbol, i) if res is None: break completion = res[len(symbol):].rstrip("(") completions.append((completion, None)) i += 1 return completions
def __read_input(self): readline.set_completer(rlcompleter.Completer(self.__vars).complete) readline.parse_and_bind("tab: complete") if os.path.exists(self.HistoryFile.value): readline.read_history_file(self.HistoryFile.value) while (True): try: line = raw_input('\001' + print_green + '\002' + self.Prompt.value + '\001' + print_reset + '\002') self.__input_queue.put(line) except: print "Exiting GuaVe, press Ctrl-C to kill guacamole..." #sys.exit(0) break