我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用readline.get_current_history_length()。
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 get_history_items(): num_items = readline.get_current_history_length() + 1 return [ readline.get_history_item(i) for i in range(1, num_items) ]
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 eventFilter(self, source, event): # Console Input if source is self.ui.console_input: if event.type() == QEvent.KeyPress: if event.key() in (Qt.Key_Enter, Qt.Key_Return): command = self.ui.console_input.text() if command != "": readline.add_history( command ) self.length = readline.get_current_history_length() self.index = -1 if event.key() == Qt.Key_Up: if self.index < self.length: self.index += 1 command = readline.get_history_item( self.length - self.index ) self.ui.console_input.setText( command ) if event.key() == Qt.Key_Down: if self.index > 0: self.index -= 1 command = readline.get_history_item( self.length - self.index ) self.ui.console_input.setText( command ) return False return False
def process_history(): """Processes python shell history to an array of code lines""" end_index = len(PySession.ipython_history) - 1 if PySession.is_ipython \ else readline.get_current_history_length() lines_of_code = [] for i in range(PySession.start_index, end_index): if i in PySession.wrong_code_lines: continue if PySession.is_ipython: line = PySession.ipython_history[i] else: line = readline.get_history_item(i) # remove 'exit' and PySession keywords from code if line.strip() in ['PySession.local()', 'PySession.gist()', 'PySession.off()', 'exit', 'exit()']: continue lines_of_code.append(line) if len( lines_of_code) > 0 and lines_of_code[-1] != '\n': # adding extra last newline lines_of_code.append('\n') return lines_of_code
def print_history (self): length = readline.get_current_history_length() for i in range(1, length + 1): cmd = readline.get_history_item(i) print("{:<5} {:}".format(i, cmd))
def get_history_item (self, index): length = readline.get_current_history_length() if index > length: print(format_text("please select an index between {0} and {1}".format(0, length))) return None return readline.get_history_item(index)
def get_total(self): return readline.get_current_history_length()
def __init__(self,cmdcomplete,init_flag=True): self.text = "" self.matches = [] self.cmdcomplete = cmdcomplete self.symbols = [] self.index = 0 self.cleanup_flag = True self.init_flag = init_flag self.session_start_index = 0 self.HISTLEN = 2000 self.HISTFILE = ".atrophy-history" self.DEFAULT_HIST_DISPLAY_LEN = 20 self.delims = readline.get_completer_delims() readline.set_completer_delims(self.delims.replace("/",'')) self.delims = readline.get_completer_delims() readline.set_completer_delims(self.delims.replace("?",'')) self.delims = readline.get_completer_delims() readline.set_completer_delims(self.delims.replace("@",'')) readline.parse_and_bind('tab: complete') readline.set_completer(self.complete) # persistant commands that actually affect a session # (e.g. breakpoints, mem writes, comments) self.project_cmds = [ "sd", "b", "db", "sb","#", "//" ] if self.init_flag == True: self.init_flag = False try: readline.read_history_file(self.HISTFILE) self.session_start_index = readline.get_current_history_length() readline.set_history_length(self.HISTLEN) except Exception as e: pass atexit.register(self.on_exit,self.HISTFILE)
def print_history(self,count=0): buf = "" length = readline.get_current_history_length() if count == 0: count = self.DEFAULT_HIST_DISPLAY_LEN for i in range(length-count,length): tmp = readline.get_history_item(i) if tmp: buf += tmp buf += "\n" return buf
def save_project(self,proj_name): session_length = readline.get_current_history_length() project_file = ".atrophy-project-%s" % proj_name project_buff = "" try: # same directory with open(project_file,"r") as f: project_buff = f.read() except: # project == full path??? try: with open(proj_name,"r") as f: project_buff = f.read() project_file = proj_name except: ## no file found pass for i in range(self.session_start_index,session_length,-1): buf = readline.get_history_item(i) if buf: cmd = buf.split(" ")[0] if cmd in self.project_cmds: project_buff += buf project_buff += "\n" with open(project_file,"w") as f: f.write(project_buff)
def do_history(self, _line): """ history Show previously executed commands. """ try: import readline hist = readline.get_current_history_length() for idx in range(1, hist + 1): self.log(readline.get_history_item(idx)) except ImportError: pass
def init(): stdout.write("\033[95m----------------------------------------------------------------\n") if os.getenv('PYSESSION_SAVE_OFF'): PySession.off() stdout.write(BANNER_OFF) elif os.getenv('PYSESSION_SAVE_LOCALLY'): PySession.local() stdout.write(BANNER_LOCAL) else: stdout.write(BANNER_GIST) if os.getenv('PYSESSION_SAVE_OFF'): stdout.write(BANNER_ENABLE) else: stdout.write(BANNER_DISABLE) stdout.write(BANNER_SWITCH) stdout.write("----------------------------------------------------------------\033[0m\n") PySession.load_history_urls() try: from IPython import get_ipython PySession.ipython_history = get_ipython().pt_cli.application.buffer.history PySession.is_ipython = True except (ImportError, AttributeError): pass if PySession.is_ipython: PySession.start_index = len(PySession.ipython_history) def custom_hook(shell, etype, evalue, traceback, tb_offset=None): PySession.wrong_code_lines.append( len(PySession.ipython_history) - 1) shell.showtraceback((etype, evalue, traceback), tb_offset=tb_offset) get_ipython().set_custom_exc((Exception,), custom_hook) else: readline.add_history('') # A hack for a strange bug in 3 < Py <3.5.2 PySession.start_index = readline.get_current_history_length() + 1 default_hook = sys.excepthook def custom_hook(etype, evalue, traceback): PySession.wrong_code_lines.append( readline.get_current_history_length()) default_hook(etype, evalue, traceback) sys.excepthook = custom_hook
def enablerlcompleter(): """Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. If the readline module can be imported, the hook will set the Tab key as completion key and register ~/.python_history as history file. This can be overriden in the sitecustomize or usercustomize module, or in a PYTHONSTARTUP file. """ def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # 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 # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history) sys.__interactivehook__ = register_readline