我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用readline.read_history_file()。
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 setup(self): """ Initialization of third-party libraries Setting interpreter history. Setting appropriate completer function. :return: """ if not os.path.exists(self.history_file): open(self.history_file, 'a+').close() readline.read_history_file(self.history_file) readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, self.history_file) readline.parse_and_bind('set enable-keypad on') readline.set_completer(self.complete) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete")
def input_loop(): if os.path.exists(HISTORY_FILENAME): readline.read_history_file(HISTORY_FILENAME) print('Max history file length:', readline.get_history_length()) print('Startup history:', get_history_items()) try: while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break if line: print('Adding {!r} to the history'.format(line)) finally: print('Final history:', get_history_items()) readline.write_history_file(HISTORY_FILENAME) # Register our completer function
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 __exit__(self, ex_tp, ex_val, ex_tb): if not haveReadline: return False try: # update the history for this project readline.write_history_file(self.historyFile) except Exception as E: print "Failed to write history to {0} - {1}".format(self.historyFile, E) # put back the original history! readline.clear_history() readline.read_history_file(self.oldhistFile) os.unlink(self.oldhistFile) # and put back the old completer readline.set_completer(self.oldCompleter) # linegenerators, pass one of these to the "run" # method of the CommandLineInterface object #import ctypes #rllib = ctypes.cdll.LoadLibrary("libreadline.so") #rl_line_buffer = ctypes.c_char_p.in_dll(rllib, "rl_line_buffer") #rl_done = ctypes.c_int.in_dll(rllib, "rl_done")
def setup_readline_history(histfn): import readline try: readline.read_history_file(histfn) except IOError: # guess it doesn't exist pass def save(): try: readline.write_history_file(histfn) except IOError: print ("bad luck, couldn't save readline history to %s" % histfn) import atexit atexit.register(save)
def hook_readline_hist(): try: import readline except ImportError: return histfile = os.environ['HOME'] + '/.web_develop_history' # ??????????????? readline.parse_and_bind('tab: complete') try: readline.read_history_file(histfile) except IOError: pass # It doesn't exist yet. def savehist(): try: readline.write_history_file(histfile) except: print 'Unable to save Python command history' atexit.register(savehist)
def load_history(self): global readline if readline is None: try: import readline except ImportError: return if self.history_file_full_path is None: folder = os.environ.get('USERPROFILE', '') if not folder: folder = os.environ.get('HOME', '') if not folder: folder = os.path.split(sys.argv[0])[1] if not folder: folder = os.path.curdir self.history_file_full_path = os.path.join(folder, self.history_file) try: if os.path.exists(self.history_file_full_path): readline.read_history_file(self.history_file_full_path) except IOError: e = sys.exc_info()[1] warnings.warn("Cannot load history file, reason: %s" % str(e))
def pre_input(self, completefn): if self.raw_input: if HAVE_READLINE: import atexit self.old_completer = readline.get_completer() # Fix Bug #3129: Limit the history size to consume less memory readline.set_history_length(self.historysize) readline.set_completer(completefn) readline.parse_and_bind(self.completekey+": complete") try: readline.read_history_file() except IOError: pass atexit.register(readline.write_history_file) self.havecolor = True if mswindows and self.enablecolor: self.cwrite = readline.GetOutputFile().write_color else: self.cwrite = self.stdout.write
def load_history(self): global readline if readline is None: try: import readline except ImportError: return if self.history_file_full_path is None: folder = os.environ.get('USERPROFILE', '') if not folder: folder = os.environ.get('HOME', '') if not folder: folder = os.path.split(sys.argv[0])[1] if not folder: folder = os.path.curdir self.history_file_full_path = os.path.join(folder, self.history_file) try: if os.path.exists(self.history_file_full_path): readline.read_history_file(self.history_file_full_path) except IOError, e: warnings.warn("Cannot load history file, reason: %s" % str(e))
def init_readline(complete_method, histfile=None): """Init the readline library if available.""" try: import readline readline.parse_and_bind("tab: complete") readline.set_completer(complete_method) string = readline.get_completer_delims().replace(':', '') readline.set_completer_delims(string) if histfile is not None: try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) except: print('readline is not available :-(')
def cmdloop_with_history(self): """ Better command loop, with history file and tweaked readline completion delimiters. """ old_completer_delims = readline.get_completer_delims() if self.histfile is not None: try: readline.read_history_file(self.histfile) except IOError: pass try: readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars))) self.cmdloop() finally: if self.histfile is not None and readline.get_current_history_length(): readline.write_history_file(self.histfile) readline.set_completer_delims(old_completer_delims)
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 init_history(self, histfile): #readline.parse_and_bind("bind ^I rl_complete") # Register our completer function readline.set_completer(SimpleCompleter(G.cmmands.keys()).complete) #readline.set_completer(TabCompleter().complete) ### Add autocompletion if 'libedit' in readline.__doc__: readline.parse_and_bind("bind -e") readline.parse_and_bind("bind '\t' rl_complete") else: readline.parse_and_bind("tab: complete") # Use the tab key for completion #readline.parse_and_bind('tab: complete') if hasattr(readline, "read_history_file"): try: readline.read_history_file(histfile) except: pass atexit.register(self.save_history, histfile)
def _load_history(self): try: hist_file = self.hist_file() if hist_file: readline.read_history_file(os.path.expanduser(hist_file)) except FileNotFoundError: pass
def init_readline(self): try: readline.read_history_file(".pupy_history") except Exception: pass self.init_completer()
def init_readline(self): """Activates history and tab completion """ # - mainly borrowed from site.enablerlcompleter() from py3.4+ # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. 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') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # see: http://bugs.python.org/issue5845#msg198636 try: readline.read_history_file(config['HISTFILE']) except IOError: pass atexit.register(readline.write_history_file, config['HISTFILE']) readline.set_history_length(config['HISTSIZE']) # - replace default completer readline.set_completer(self.improved_rlcompleter()) # - enable auto-indenting readline.set_pre_input_hook(self.auto_indent_hook)
def __init__(self, ui, config, parent=None): """ Loads default configuration for console_log. A new thread is spawned to which the interpreter is moved. This is done to increase the responsiveness of the main user interface. :param ui: used to access 'main.ui' methods :param config: used to configure classes """ super(ConsoleProperty, self).__init__(parent) self.ui = ui self.config = config # Document self.ui.console_log.document().setMaximumBlockCount( self.config["Console"]["Scrollback Buffer"] ) self.ui.console_log.setWordWrapMode(QTextOption.WrapAnywhere) # Console Input History self.index = -1 self.length = 0 readline.set_history_length(50) self.ui.console_input.installEventFilter(self) try: open(self.HISTORY_PATH, "x") except FileExistsError: readline.read_history_file(self.HISTORY_PATH) self.length = readline.get_current_history_length() # Display self.display = PythonDisplay(self.ui, self.config, self)
def preloop(self): if os.path.exists(self.hist_file): readline.read_history_file(self.hist_file)
def init_history(self): try: readline.read_history_file(self.hist_file) readline.set_history_length(HISTORY_FILE_SIZE) readline.write_history_file(self.hist_file) except IOError: readline.write_history_file(self.hist_file) atexit.register(self.save_history)
def init_history(self, histfile): readline.parse_and_bind("tab: complete") if hasattr(readline, "read_history_file"): try: readline.read_history_file(histfile) except IOError: pass atexit.register(self.save_history, histfile)
def __enter__(self): # we only do something if we have readline if not haveReadline: return self ## Set up the new history context self.historyFile = os.path.join( os.getenv('HOME'), ".{0}.history".format(self.basename)) (h, self.oldhistFile) = tempfile.mkstemp(prefix=self.basename, suffix=".hist", dir="/tmp") # only need the filename, really os.close(h) readline.write_history_file(self.oldhistFile) readline.clear_history() # if reading the old history fails, fail silently # (the file might not exist yet) try: readline.read_history_file(self.historyFile) except: pass # store the old completer, install our own one readline.parse_and_bind("tab: complete") #readline.parse_and_bind("C-c: backward-kill-line") self.oldCompleter = readline.get_completer() readline.set_completer(self.completer) return self # clean up the context
def _load_history(self): """Load history file and register dump on exit.""" # Create a file without truncating it in case it exists. open(config.history_path, 'a').close() readline.set_history_length(100) try: readline.read_history_file(config.history_path) except IOError: pass atexit.register(readline.write_history_file, config.history_path)
def init_python_session(): """Construct new Python session. """ from code import InteractiveConsole class SymPyConsole(InteractiveConsole): """An interactive console with readline support. """ def __init__(self): InteractiveConsole.__init__(self) try: import readline except ImportError: pass else: import os import atexit readline.parse_and_bind('tab: complete') if hasattr(readline, 'read_history_file'): history = os.path.expanduser('~/.sympy-history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history) return SymPyConsole()
def main(): url = sys.argv[1] context['url'] = url pkg = app.dispatch_url(url) context['pkg'] = pkg for item in pkg.to_dict().items(): print '{} = {}'.format(*item) def prepare_readline(): import os import readline import atexit readline.parse_and_bind('tab: complete') histfile = os.path.expanduser("~/.daenerys_history") try: readline.read_history_file(histfile) except IOError: pass def savehist(histfile): readline.write_history_file(histfile) atexit.register(savehist, histfile) del atexit try: from IPython.terminal.interactiveshell import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=context) shell.mainloop() except ImportError: import code shell = code.InteractiveConsole(locals=context) shell.runcode(prepare_readline.__code__) shell.interact()
def load_console_history(self): if os.path.exists(self._history_file): readline.read_history_file(self._history_file) return
def InitReadline(complete_cb): home_dir = os.environ.get('HOME') if home_dir is None: home_dir = util.GetHomeDir() if home_dir is None: print("Couldn't find home dir in $HOME or /etc/passwd", file=sys.stderr) return history_filename = os.path.join(home_dir, 'oil_history') try: readline.read_history_file(history_filename) except IOError: pass atexit.register(readline.write_history_file, history_filename) readline.parse_and_bind("tab: complete") # How does this map to C? # https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC45 readline.set_completer(complete_cb) # NOTE: This apparently matters for -a -n completion -- why? Is space the # right value? # http://web.mit.edu/gnu/doc/html/rlman_2.html#SEC39 # "The basic list of characters that signal a break between words for the # completer routine. The default value of this variable is the characters # which break words for completion in Bash, i.e., " \t\n\"\\'`@$><=;|&{("" # # Hm I don't get this. readline.set_completer_delims(' ')
def init_readline(self): "Initialize the readline functionality to enable console history." if self.hub_history_file is not None: readline.set_history_length(self.hub_history_length) try: readline.read_history_file(self.hub_history_file) except IOError: pass atexit.register(readline.write_history_file, self.hub_history_file)
def load_history(): readline.set_history_length(10000) try: if os.path.exists(history_file_path): readline.read_history_file(history_file_path) except IOError: pass
def interact(mgr): """ Shell setup function. This function will setup the library, create the default namespace with shell symbols, setup the history file, the autocompleter and launch a shell session. """ print('Engine nodes available for communication:') print(' {}'.format(', '.join(mgr.nodes.keys()))) # Create and populate shell namespace ns = { 'topology': mgr } for key, enode in mgr.nodes.items(): ns[key] = enode # Configure readline, history and autocompleter import readline histfile = join(expanduser('~'), '.topology_history') if isfile(histfile): try: readline.read_history_file(histfile) except IOError: log.error(format_exc()) register(readline.write_history_file, histfile) completer = NamespaceCompleter(ns) readline.set_completer(completer.complete) readline.parse_and_bind('tab: complete') # Python's Interactive from code import interact as pyinteract pyinteract('', None, ns)
def main(argc, argv): parser = argparse.ArgumentParser(description='VM32 Debuuger') parser.add_argument('-d', '--debug', action='store_true', dest='debug', help='Display debug information (DEBUG)') parser.add_argument('memoryImage', metavar='memory image', type=argparse.FileType('r'), help='Image to be loaded into the system memory') arguments = parser.parse_args(argv[1:]) #enable logging if arguments.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) cpu = CPU(arguments.memoryImage.read()) #history stuff, if it fails don't worry and carry on try: historyPath = os.path.expanduser("~/.vm32history") import readline def save_history(historyPath=historyPath): readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) import atexit atexit.register(save_history) except Exception: print "GNU readline support not available" DebuggerShell(cpu).cmdloop()