def restore_old_history(self): readline.clear_history() for line in self._oldHistory: if line is None: continue readline.add_history(line) self._oldHistory = []
def __init__(self): """Class constructor. Read class docstring for more details""" pprint_try_use_unicode() self.variables = {} self.options = { "implicit_multiplication": True, "num_tolerance": 1e-10, "integration_variable": None, "diff_variable": None, "tau_kills_pi": False, "always_sub": False, "always_num": False} self.update_completer() self.sub = False self.num = False # History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . path = join(dirname(abspath(__file__)), ".symi_history") try: with open(path, "r") as f: readline.clear_history() history = f.readlines() for his in history: his = his.strip() if his == "": continue readline.add_history(his) except FileNotFoundError: pass print(self.welcome_msg)
def input_callback(self, prompt, completions=True): # Setup subedit self.curs_set(1) self.callbacks["set_var"]("input_do_completions", completions) self.callbacks["set_var"]("input_prompt", prompt) self.input_box.reset() self.input_box.refresh() curses.doupdate() self.pseudo_input_box.keypad(0) r = raw_readline() if not r: r = "" self.pseudo_input_box.keypad(1) # Only add history for commands, not other prompts if completions: readline.add_history(r) self.callbacks["set_var"]("input_prompt", "") self.input_box.reset() self.input_box.refresh() curses.doupdate() self.curs_set(0) return r
def _exec_from_file(self, filename, quiet=False, skip_history=False, print_comments=config['POST_EDIT_PRINT_COMMENTS']): previous = '' for stmt in open(filename): # - skip over multiple empty lines stripped = stmt.strip() if stripped == '' and stripped == previous: continue if not quiet: if stripped.startswith('#'): if print_comments: self.write(grey("... {}".format(stmt), bold=False)) else: self.write(cyan("... {}".format(stmt))) if not stripped.startswith('#'): line = stmt.strip('\n') if line and not line[0].isspace(): source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() self.buffer.append(line) if line.strip() and not skip_history: readline.add_history(line) previous = stripped self.push('')
def readline(prompt="user> "): global history_loaded #检验history是否载入,若没有,先载入 if not history_loaded: history_loaded = True try: with open(history_file, 'r') as f: for line in f.readlines(): pyreadline.add_history(line.rstrip("\r\n")) pass except IOError: # pass #读用户输入行 try: line = input(prompt) pyreadline.add_history(line) with open(history_file, 'a') as f: f.write(line + '\n') except IOError: pass except EOFError: return None return line
def exec_cmd(cmdline): """Interpret a command.""" cmd, arg = _parse_cmdline(cmdline) if not cmd: print('Bad command.') else: cmd_callable = get_cmd(cmd) if not cmd: print('Type a command. Try \'help\'.') elif cmd_callable: try: cmd_callable(arg) except ImproperArgError as e: print(str(e)) except UsageError as e: print('usage: ' + cmd + ' ' + str(e)) except MissingDeckError: print('No active deck. Create a new deck with the \'deck\' ' 'command.') except cards.ScrapeError as e: print('Scrape failed: ' + str(e)) if 'readline' in sys.modules: readline.add_history(cmdline) else: print('%s is not a command. Try \'help\'.' % str(cmd)) return True
def get_meta(prompt, default, default_list): default_count = 0 if default_list: if not default: count = len(default_list) if count == 0: default = '' else: if type(default_list[0]) is str: default = default_list[0] else: default = default_list[0][0] default_count = count - 1 readline.clear_history() default_list.reverse() for d in default_list: if type(d) is str: readline.add_history(d) else: readline.add_history(d[0]) if default_count > 0: full_prompt = ('{} [{}](+ {} more): '. format(prompt, default, default_count)) else: full_prompt = ('{} [{}]: '. format(prompt, default)) result = input(full_prompt) if result == '': return default else: return result
def _push_readline_history(history, clear_history=True): """Restores readline's history and optionally clears it first (default)""" if rl_type != RlType.NONE: if clear_history: readline.clear_history() for line in history: readline.add_history(line)
def main(): global es_host, es_port, request_host parser = argparse.ArgumentParser() parser.add_argument( '-host', help='elasticsearch host (default is http://localhost)') parser.add_argument('-port', help='elasticsearch port (default is 9200)') args = parser.parse_args() es_host = args.host if args.host else es_host es_port = args.port if args.port else es_port es_uri = (es_host + ':' + es_port).replace('http://', '') request_host = 'http://' + es_uri completer = CustomCompleter(support_commands) readline.set_completer(completer.complete) readline.parse_and_bind('tab: complete') check_connection() input_text = es_uri + '> ' while True: try: user_input = input(input_text).lstrip().rstrip() readline.add_history(user_input) command_split_list = user_input.split(' ') command_master = command_split_list[0] if command_master == 'exit': sys.exit(1) elif command_master == 'help': help_input() elif command_master == 'get': command_get(command_split_list) elif command_master == 'del': command_del(command_split_list) elif command_master == 'delete_by_query': command_delete_by_query(command_split_list) elif command_master == 'cat': command_cat(command_split_list) elif command_master == 'info': command_info() elif command_master == 'match_all': command_match_all(command_split_list) elif command_master == 'match': command_match(command_split_list) elif command_master == 'analyze': command_analyze(command_split_list) elif command_master == 'settings': command_settings(command_split_list) elif command_master.replace(' ', '') == '': continue else: print("(error) ERR unknown command '" + user_input + "'") except KeyboardInterrupt: print('thank you!') sys.exit(0)
def run(self): try: import readline except ImportError: return hist = builtins.__xonsh_history__ while self.wait_for_gc and hist.gc.is_alive(): time.sleep(0.011) # gc sleeps for 0.01 secs, sleep a beat longer files = hist.gc.files() i = 1 for _, _, f in files: try: lj = LazyJSON(f, reopen=False) for command in lj['cmds']: inp = command['inp'].splitlines() for line in inp: if line == 'EOF': continue readline.add_history(line) if RL_LIB is not None: RL_LIB.history_set_pos(i) i += 1 lj.close() except (IOError, OSError, ValueError): continue
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 _run(self): try: while self.running(): with self._lock: if self._code: codeColor = Fore.RED else: codeColor = Fore.GREEN cliJoined = ' '.join(self._cli) codePart = '{}{}{}'.format( codeColor, self._code, Style.RESET_ALL) cliPart = '{}{}{}'.format( Fore.LIGHTCYAN_EX, cliJoined, Style.RESET_ALL) line = input('[{}] ({}) > '.format(codePart, cliPart)) if readline.get_history_length() == 0: readline.add_history(line) elif line != readline.get_history_item(readline.get_current_history_length()): readline.add_history(line) self._execute(shlex.split(line)) except EOFError: self.stop() try: readline.write_history_file(self._historyFile) except: print() print('Could not save history file: {}'.format( self._historyFile))
def _run(self): """Go through all commands on a pseudo-shell, and execute them, caching the passphrase at some point.""" print "Welcome to SFLvault. Type 'help' for help." prompt = "SFLvault> " while True: cmd = raw_input(prompt) if not cmd: continue # Get sys.argv-like parameters args = shlex.split(cmd) # Local (shell) cmds take precedence over SFLvaultCommand cmds. if len(args) and hasattr(self, args[0]): getattr(self, args[0])() else: parser = NoExitParser(usage=optparse.SUPPRESS_USAGE) runcmd = SFLvaultCommand(self.config, self.vault, parser) try: runcmd._run(args) except ExitParserException, e: pass if hasattr(runcmd, 'next_command') \ and platform.system() != 'Windows': print "[Added to shell history: %s]" % runcmd.next_command readline.add_history(runcmd.next_command)
def append(self, event): ''' Append a new history event. :param str event: event to append ''' readline.add_history(event)
def executeOneCmd(self): line = '' if len(self.doLines) > 0: if self.doPtr == len(self.doLines): self.doLines = [] self.doPtr = 0 line = (input(self.getPromptStr())) else: line = self.doLines[self.doPtr] readline.add_history(line) self.doPtr += 1 self.printPrompt() print(line) else: line = (input(self.getPromptStr())) gSet.myUsg.start() cmd = self.RegCmd(line.split()[0]) if cmd != None: if cmd.isQuitCmd(): return cmd.execute(line) cmd.execute(line) else: print("Unknown command \"" + line.split()[0] + "\"\n") gSet.myUsg.end() return True
def input(self, prompt, continuation_prompt): """Get input from the user, similar to the Python input() function. The prompt is printed before the first line of input. If the input line ends with the continuation string, then additional lines are requested, using the continuation prompt.""" lines = [] while True: line = input(prompt if len(lines) == 0 else continuation_prompt) # The len(lines) > 0 check is needed to fix bug 41. if len(line) > 0 or len(lines) > 0: history_length = readline.get_current_history_length() if history_length > 0: readline.remove_history_item(history_length - 1) # If line was recalled from history, then convert to its original multiline form. from_history = self._multiline(line) if from_history is None: # Wasn't from history lines.append(line) else: lines = from_history line = lines[-1] if not line.endswith(self.continuation): break # Store history as a single line with continuations and line breaks. readline.add_history('\n'.join(lines)) # Return a single string without continuations and line breaks. lines[-1] += self.continuation return ''.join([line[:-len(self.continuation)] for line in lines])
def set_context(self, name): """Set the current history context. This swaps in a new history context by loading the history from the contexts filename. The old context's history is saved first. """ if name not in self.contexts: raise ValueError("Invalid history context: %s" % name) if self.current: if name == self.current.name: return self.save() self.current = self.contexts[name] try: readline.clear_history() if self.current.obj: with open(self.current.filename, 'r') as f: lines = pickle.load(f) for line in lines: readline.add_history(line) else: readline.read_history_file(self.current.filename) except IOError: pass
def _process_input(self): if sys.version_info[0] >= 3: input_impl = input else: input_impl = raw_input while True: self._idle.wait() expression = "" line = "" while len(expression) == 0 or line.endswith("\\"): try: if len(expression) == 0: line = input_impl(">>> ") else: line = input_impl("... ") except EOFError: return if len(line.strip()) > 0: if len(expression) > 0: expression += "\n" expression += line.rstrip("\\") if HAVE_READLINE: readline.add_history(expression) self._idle.clear() self._reactor.schedule(lambda: self._send_expression(expression))
def wrapper(*args, **kwargs): try: import readline handle_readline = True except ImportError: handle_readline = False if handle_readline: # backup & reset readline completer old_readline_completer = readline.get_completer() readline.set_completer((lambda x: x)) # backup & reset readline history old_readline_history = [] hist_sz = readline.get_current_history_length() for i in range(1, hist_sz + 1): line = readline.get_history_item(i) old_readline_history.append(line) readline.clear_history() try: retval = function(*args, **kwargs) finally: if handle_readline: # restore old readline completer readline.set_completer(old_readline_completer) # restore old readline history readline.clear_history() for line in old_readline_history: readline.add_history(line) return retval
def input(self, prompt=None, *, history=True): """Read a single line Parameters ---------- history: bool, optional append read line to history (only if ``stdin`` is ``None``) (defaults to ``True``) Returns ------- str the read line """ if prompt is None: prompt = self.__prompt if self.__stdin is not None: try: line = next(self.__stdin) if readline_module: readline_module.add_history(line.rstrip('\n')) return line except StopIteration: return None else: return input_function(prompt=prompt, history=history) # pylint: disable=bad-builtin
def add_item(self, line, force=False): # Kludge. pyreadline is a pain in the ass. from pyreadline import lineobj from pyreadline.unicode_helper import ensure_unicode line = ensure_unicode(line.rstrip()) readline.add_history(lineobj.ReadLineTextBuffer(line))
def run(self): with self.connect() as client: commands = Commands(Actions(client)) readline.set_completer(commands.completer()) readline.set_completer_delims("\t") readline.parse_and_bind("tab: complete") def sigint_handler(signum, frame): commands.lookup("cont").sigint() signal.signal(signal.SIGINT, sigint_handler) while True: line = input("(dbg): ").strip() if line != "": readline.add_history(line) try: cmd = commands.lookup(line) msg = cmd(line) except CommandNotFound as e: if e.command != "": print(e) except ActionError as e: print("ActionError") print(e.message) raise e
def show_operation_dialog(): running = True output = None all_history = [ readline.get_history_item(i) for i in range(1, readline.get_current_history_length() + 1) ] readline.clear_history() while running: try: line = raw_input( 'Type "yes" or "no" to confirm or decline the operation: ') except (KeyboardInterrupt, EOFError): break if line == 'yes': output = True elif line == 'no': output = False else: print 'Invalid response' # Remove whatever the user typed so we don't see "yes" or "no" in the history readline.remove_history_item(readline.get_current_history_length() - 1) if output is not None: break for item in all_history: readline.add_history(item) return output or False
def init(cls): """Initialize a nice environment to run in """ import os cls.debug = os.getenv("PYTHONRC_DEBUG") if os.getenv("NOPYTHONRC"): # Not loading the python environment cls.dp("Skipping loading the pythonrc environment stuff") return try: import readline except ImportError: print("Failed to load readline") readline = None cls.readline = readline if readline: # Set the history file cls.histfile = os.path.join(os.getenv("HOME", "."), ".python_history") cls.dp("Using history file '%s'" % cls.histfile) # Read the history file if os.path.exists(cls.histfile): readline.read_history_file(cls.histfile) cls.dp("Using existing history information") else: cls.dp("Creating new history file") # Set the number of history items to 3000 readline.set_history_length(3000) cls.dp("History size set to 3000") # Put a marker for the starting time. readline.add_history("# starting %s" % cls.strtime()) cls.dp("Marked start of history file") # Allow Tab Completion import rlcompleter # This sets up python specific completion readline.parse_and_bind("tab: complete") cls.dp("Started completion") else: cls.dp("No readline available") # Set the prompts import sys sys.ps1 = "python%s> " % ".".join(map(str, sys.version_info[:2])) sys.ps2 = " " * (len(sys.ps1) - 2) + "> " cls.dp("Set prompts") # The the exit function import atexit atexit.register(cls.exit) cls.dp("Registered exit function")
def loop(self): """ Starts the command loop loop() -> None """ # Process commands # NOTE: doesn't work with ; inside quoted arguments cmds = [arg.strip() for arg in self._args.command.split(';')] if self._args.command else [] self._entry() while True: self._preInput() try: if len(cmds): res = cmds.pop(0) print(">>> " + res) readline.add_history(res) else: res = input('>>> ').strip() except EOFError: print(colored("(EOF)", 'yellow')) break self.runCommandRaw(res) self._postInput() self._exit()
def edit_track(self, files): input = raw_input('[A]ccept, 1-%d to edit name, s/pattern/repl/g: ' % len(files)) try: filename = files.keys()[int(input) - 1] old_name = files[filename] readline.add_history(old_name) new_name = raw_input('New name [%s] (press up): ' % old_name) files[filename] = new_name or old_name except (ValueError, IndexError): if input.upper() in ('', 'Y'): return True if input.startswith('s/'): elems = [re.escape(x) for x in input.split('/')] if len(elems) != 4: print "W: Malformed regular expression" return False count = 0 for filename, name in files.iteritems(): new_name = re.sub(elems[1], elems[2], name) if name != new_name: files[filename] = new_name count += 1 print "I: %d track(s) changed" % count return False
def _process_input(self): if sys.version_info[0] >= 3: input_impl = input else: input_impl = raw_input while True: self._idle.wait() expression = "" line = "" while len(expression) == 0 or line.endswith("\\"): try: if len(expression) == 0: line = input_impl(">>> ") else: line = input_impl("... ") except EOFError: return if len(line.strip()) > 0: if len(expression) > 0: expression += "\n" expression += line.rstrip("\\") if HAVE_READLINE: readline.add_history(expression) self._idle.clear() self._reactor.schedule( lambda: self._send_expression(expression))
def _read_file(self, fname): """ Generator to read ScriptLine objects from the file named `fname`. """ lno = 0 # Ignore leading blank lines that would be treated as pauses inhibit_pause = True with open(fname, 'r') as f: for line in f: # Track the line number lno += 1 # Parse the line sc_line = ScriptLine(fname, lno, line) # Process pauses if sc_line.type == 'pause': if inhibit_pause: # Apply pause inhibition continue # Inhibit future pausing inhibit_pause = True else: # Not inhibiting any more pauses inhibit_pause = False # Add the line to the history readline.add_history(sc_line.raw) # Yield the line yield sc_line
def edit_track(self, files): input = raw_input( '[A]ccept, 1-%d to edit name, s/pattern/repl/g: ' % len(files) ) try: filename = files.keys()[int(input) - 1] old_name = files[filename] readline.add_history(old_name) new_name = raw_input('New name [%s] (press up): ' % old_name) files[filename] = new_name or old_name except (ValueError, IndexError): if input.upper() in ('', 'Y'): return True if input.startswith('s/'): elems = [re.escape(x) for x in input.split('/')] if len(elems) != 4: print "W: Malformed regular expression" return False count = 0 for filename, name in files.iteritems(): new_name = re.sub(elems[1], elems[2], name) if name != new_name: files[filename] = new_name count += 1 print "I: %d track(s) changed" % count return False
def _add_line_to_history(self, line): """Adds the given line to readline history, only if the line is non-empty. If the line starts with a prompt symbol, the prompt is stripped from the line. """ if line and HAS_READLINE: readline.add_history(line)
def exec_cmd(cmdline): """Interpret a command.""" cmd, arg = _parse_cmdline(cmdline) if not cmd: print("Bad command.") else: cmd_callable = get_cmd(cmd) if not cmd: print("Type a command. Try 'help'.") elif cmd_callable: try: cmd_callable(arg) except ImproperArgError as e: print(str(e)) except UsageError as e: print("usage: " + cmd + " " + str(e)) except MissingDeckError: print("No active deck. Create a new deck with the 'deck' " "command.") except cards.ScrapeError as e: print("Scrape failed: " + str(e)) if "readline" in sys.modules: readline.add_history(cmdline) else: print("%s is not a command. Try 'help'." % str(cmd)) return True
def append(self, event): """ Append a new history event. :param str event: event to append """ readline.add_history(event)
def _process_edit_cmd(self): # - setup the edit buffer fd, filename = mkstemp('.py') # - make a list of all lines in session history, commenting any # non-blank lines. lines = [] for line in self.session_history: line = line.strip('\n') if line: lines.append('# {}'.format(line)) else: lines.append(line) # - join list into a single string delimited by \n and write to a # temporary file. lines = '\n'.join(lines) os.write(fd, lines.encode('utf-8')) os.close(fd) # - shell out to the editor os.system('{} {}'.format(EDITOR, filename)) # - process commands lines = open(filename) os.unlink(filename) for stmt in lines: self.write(cyan("... {}".format(stmt))) line = stmt.strip('\n') if not line.strip().startswith('#'): self.push(line) readline.add_history(line) return ''
def set_context(self, name): """Set the current history context. This swaps in a new history context by loading the history from the contexts filename. The old context's history is saved first. """ if name not in self.contexts: raise ValueError("Invalid history context: %s" % name) if self.current: if name == self.current.name: return self.save() self.current = self.contexts[name] try: readline.clear_history() if self.current.obj: with open(self.current.filename, "r") as f: lines = pickle.load(f) for line in lines: readline.add_history(line) else: readline.read_history_file(self.current.filename) except IOError: pass
def user_interface(): global block, terminate, forever_back, wait_start spaces = ' ' cmds = database.cmds_get() for cmd in cmds: readline.add_history(cmd['command']) while not terminate: try: line = raw_input(prompt()) block = True try: done = process_line(line) while not done: done = process_line(line) except KeyboardInterrupt: wait_start = None print 'Command cancelled:',line block = False sys.stdout.write(forever_back+spaces+forever_back) sys.stdout.flush() except EOFError: print '\nPrune exiting for Ctl-d...' sys.exit(0) except KeyboardInterrupt: print '\nPrune exiting for Ctl-c...' return except Exception: print traceback.format_exc()
def remove_history_item(line_number, initial_history_length=None): """ Function to remove an item from the readline history since readline.remove_history_item() is not working Args: line_number (int): History line that will removed initial_history_length (int): The history length recorded at the start of the Pybash session, used for history management. If the removed line was prior to the initial history length, then this needs to be adjusted. Returns: int: If initial_history_length was provided, the adjusted initial history length is returned If not, then None is returned """ # Get all history items except for the one at line_number hist_len = readline.get_current_history_length() new_history = [ readline.get_history_item(i) for i in range(1, hist_len) if not i == line_number ] # Replace history readline.clear_history() for l in new_history: readline.add_history(l) # If initial_history_length was specified, check to see if it needs to be adjusted if initial_history_length: if line_number < initial_history_length: return initial_history_length - 1 else: return initial_history_length else: return
def multiline(self, firstline=''): full_input = [] # keep a list of the entries that we've made in history old_hist = [] if firstline: print ' ' + firstline full_input.append(firstline) while True: if hasReadline: # add the current readline position old_hist.append(readline.get_current_history_length()) if self.use_rawinput: try: line = raw_input(self.multiline_prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.multiline_prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] # chop \n if line == 'EOF': break full_input.append(line) # add the final readline history position if hasReadline: old_hist.append(readline.get_current_history_length()) cmd = '\n'.join(full_input) + '\n' if hasReadline: # remove the old, individual readline history entries. # first remove any duplicate entries old_hist = sorted(set(old_hist)) # Make sure you do this in reversed order so you move from # the end of the history up. for pos in reversed(old_hist): # get_current_history_length returns pos + 1 readline.remove_history_item(pos - 1) # now add the full line readline.add_history(cmd) locals = self.curframe.f_locals globals = self.curframe.f_globals print self.save_history() try: try: code = compile(cmd, '<stdin>', 'single') exec code in globals, locals except: print self._reprExc() finally: self.read_history()
def getInput(self): out = None if self._default == None: self._default = datetime.datetime.now(dateutil.tz.tzlocal()) readline.clear_history() # put the default value into history readline.add_history(self._formatDate(self._default)) # try to complete during typing. readline.set_completer_delims('\n;') readline.parse_and_bind("tab: complete") readline.set_completer(self.comp) # get user input until it's acceptable while out == None: inp = input(self._display + " [{}]: " .format(self._formatDate(self._default))) if inp == "?": self.printSpec() else: try: out = self.tryParse(inp.strip(), self._default) except Exception as e: # although the value is not acceptable, give user # a chance to modify it. hist = inp.strip() if len(hist) > 0: readline.add_history(inp.strip()) self.printSpec() readline.clear_history() readline.set_completer() # print(">> {}: {}".format(self._display, out.strftime("%Y/%m/%d %H:%M"))) return out
def cmdloop(self, opts): """ Interactive mode worker function :param opts: command options :type opts: options. """ self.interactive = True if not opts.nologo: CLI.version(self._progname, versioning.__version__,\ versioning.__extracontent__, fileh=sys.stdout) if opts.debug: LOGGER.setLevel(logging.DEBUG) LERR.setLevel(logging.DEBUG) #**********Handler for GUI tab tab *************** for section in self._commands: if section.startswith('_'): continue for command in self._commands[section]: self.commlist.append(command.name) for item in self.commlist: if item == "help": self.candidates[item] = self.commlist else: self.candidates[item] = [] self._redobj = TabAndHistoryCompletionClass(dict(self.candidates)) readline.set_completer(self._redobj.main_completer_handler) readline.parse_and_bind("tab: complete") #*************************************************** while True: line = input(versioning.__shortname__ + ' > ') readline.add_history(line) if not len(line): continue elif line.endswith(os.linesep): line.rstrip(os.linesep) nargv = shlex.split(line, posix=False) try: if "login " in line or line == 'login': self.app.logout() self.retcode = self._run_command(opts, nargv) self.check_for_tab_lists(nargv) except Exception as excp: self.handle_exceptions(excp) if self.opts.verbose: sys.stdout.write(u"REDFISH return code: %s\n" % self.retcode) return self.retcode
def edit(self, i): '''Edit unit i.''' suspects = self.job.units[i]['suspects'] # suspect substrings value = self.job.units[i]['value'] # unit value newval = '' status = None for suspect in suspects: print self.OUT_PROMPT, self.highlight(suspect, value) new = raw_input(self.IN_PROMPT) if new: newval = value.replace(suspect, new) print self.OUT_PROMPT, self.highlight(new, newval, 'GREEN') print status = 'edit' else: while True: input = raw_input(self.CMD_PROMPT) if input in ("?", "h", "help"): print self.EDIT_OPTS, input = raw_input(self.CMD_PROMPT) if not input: return None # do nothing elif input == 'q': return 'quit' elif input == 'r': _i, _value = self._previous if not _value: self.helper("no previous value stored!") continue self.job.units[_i]['value'] = _value # restore prev self.edit(_i) # redo edit return 'redo' elif input.startswith('o'): # omit unit if '-t' in input: self.do_tag(str(i) + input.replace("o", "", 1)) print return 'omit' elif input == 'c': self.do_context(i) status = None elif input.startswith('t'): self.do_tag("{0} -{1}".format(i, input)) status = None elif input == 'e': self.helper("use up arrow to get existing line", 4) readline.add_history(value) newval = raw_input(self.IN_PROMPT) if newval: print self.OUT_PROMPT, newval print status = 'edit' break if status == 'edit': self._previous = (i, value) # store prev index, value self.job.units[i]['value'] = newval # self.job.set_value(i, newval) return status
def handle_cmd (self): cmd = self.lines[self.line_index].get().strip() if not cmd: return op, param = self.split_cmd(cmd) func = self.ac.get(op) if func: with self.async_.tui_global_lock: func_rc = func(param) # take out the empty line empty_line = self.lines.popleft() assert(empty_line.ro_line == '') if not self.lines or self.lines[0].ro_line != cmd: self.lines.appendleft(CmdLine(cmd)) # back in self.lines.appendleft(empty_line) self.line_index = 0 readline.add_history(cmd) self.save_console_history() # back to readonly for line in self.lines: line.invalidate() assert(self.lines[0].modified == False) color = None if not func: self.last_status = "unknown command: '{0}'".format(format_text(cmd.split()[0], 'bold')) else: # internal commands if isinstance(func_rc, str): self.last_status = func_rc # RC response else: # success if func_rc is None: self.last_status = format_text("[OK]", 'green') # errors else: err_msgs = ascii_split(str(func_rc)) if not err_msgs: err_msgs = ['Unknown error'] self.last_status = format_text(clear_formatting(err_msgs[0]), 'red') if len(err_msgs) > 1: self.last_status += " [{0} more errors messages]".format(len(err_msgs) - 1) color = 'red' # trim too long lines if ansi_len(self.last_status) > TrexTUI.MIN_COLS: self.last_status = format_text(self.last_status[:TrexTUI.MIN_COLS] + "...", color, 'bold')
def terminal(self, url, pwd): hostname=urlparse.urlparse(url)[1] while True: cmnd = raw_input( hostname + '> ' ) if cmnd!='\n': readline.add_history(cmnd) print self.host.execute(cmnd)
def main(argv): parser = optparse.OptionParser() parser.add_option('-s', '--server', dest='server', help='The hostname your app is deployed on. ' 'Defaults to <app_id>.appspot.com.') parser.add_option('--secure', dest='secure', action="store_true", default=False, help='Use HTTPS when communicating ' 'with the server.') (options, args) = parser.parse_args() if not args or len(args) > 3: print >> sys.stderr, __doc__ if len(args) > 3: print >> sys.stderr, 'Unexpected arguments: %s' % args[2:] sys.exit(1) appid = args[1] if len(args) == 3: path = args[2] else: path = DEFAULT_PATH remote_api_stub.ConfigureRemoteApi(appid, path, __auth_func, servername=options.server, save_cookies=True, secure=options.secure) remote_api_stub.MaybeInvokeAuthentication() servername = options.server if not servername: servername = '%s.appspot.com' % (appid,) rpc_server = appengine_rpc.HttpRpcServer(servername, __cached_auth_func, remote_api_stub.GetUserAgent() + ' remote_driver_shell/1.0', remote_api_stub.GetSourceName(), save_cookies=True, debug_data=False, secure=options.secure) global __remote_driver_server __remote_driver_server = rpc_server os.environ['SERVER_SOFTWARE'] = 'Development (remote_driver_shell/1.0)' sys.ps1 = '%s/driver> ' % appid if readline: readline.parse_and_bind('tab: complete') atexit.register(lambda: readline.write_history_file(HISTORY_PATH)) if os.path.exists(HISTORY_PATH): readline.read_history_file(HISTORY_PATH) readline.add_history('') global __readline_history_session_start __readline_history_session_start = readline.get_current_history_length() code.interact(banner=BANNER, readfunc=__magic_input, local=globals())
def terminal(self, url, pwd): hostname = urlparse.urlparse(url)[1] while True: cmnd = raw_input(hostname + '> ') if cmnd != '\n': readline.add_history(cmnd) print self.host.execute(cmnd)
def input(self, add_to_history: str = '', prompt: str = '> ') -> str: import readline print(end=set_cursor_shape('bar')) if add_to_history: readline.add_history(add_to_history) try: return input(prompt) finally: print(end=set_cursor_shape())
def last_history(line): if line == "": return False if (readline.get_current_history_length() == 0 or readline.get_history_item( readline.get_current_history_length()) != line.encode("utf-8")): readline.add_history(line.encode("utf-8")) return True return False
def execute(self, pos, end=None): """execute history number from pos to end""" if not end: end = pos commands = [] for item in self.iterator(pos, end): commands.append(item) readline.add_history(item) exec_stub("\n".join(commands), globals())
def add_history(self, line): # Emulate HISTCONTROL=ignorespace to avoid adding to history. if line.startswith(' '): return # Emulate HISTCONTROL=ignoredups to avoid duplicate history entries. nitems = readline.get_current_history_length() lastline = readline.get_history_item(nitems) if lastline != line: readline.add_history(line)
def get_sentence(text): if text is not None: print("Previous sentences:\n", text) sentence = input("Enter a sentence: ") if READLINE_IMPORTED: readline.add_history(sentence) return sentence
def interact(banner="", local=None, stackLevel=1, frame=None, mode='interact', history=False): """Interact using the current global and local scope and history. arguments: banner -- print this text before interacting. local -- ignored history: bool or int if non-false, this many lines of history are found from the file being interacted with and inserted into the readline buffer """ if len(banner) > 0: print banner # Get data from calling frame #calling_data = inspect.stack()[stackLevel] #filename = calling_data[1] #lineno = calling_data[2] #frame = calling_data[0] #local = frame.f_locals #global_ = frame.f_globals if frame is None: frame = inspect.stack()[stackLevel][0] filename = frame.f_code.co_filename lineno = frame.f_lineno local = frame.f_locals global_ = frame.f_globals if history: new_history = [ ] if os.access(filename, os.R_OK): new_history.extend(get_history(filename, lineno)) # add lines to history, removing proper amount of whitespace for line in new_history: readline.add_history(line) # add an exit() function under the name __exit. Hopefully this # won't cause namespace collisions! local["__exit"] = sys.exit if mode == 'pdb': import pdb p = pdb.Pdb() def do_quit(self, arg): sys.exit() p.do_quit = type(p.do_quit)(do_quit, p, pdb.Pdb) p.do_q = p.do_quit p.reset() p.interaction(frame, None) #from fitz import interactnow #pdb.post_mortem(frame) else: interact2(local=local, global_=global_, banner="")
def load_history(self): """Load saved command history from local history file""" try: with file(self.history_file_name, 'r') as f: for line in f.readlines(): stripped_line = line.strip() self.history.append(stripped_line) readline.add_history(stripped_line) except IOError: pass # ignore if file cannot be read
def update(self, inc): """Update comment, handle commands. Return position increment.""" rv = 0 # position increment default is do same again if not os.path.exists(self.name): self.selected = False if not self.selected: return inc if self.comment: print self readline.add_history(self.comment) try: comment = raw_input('%s: ' % self.repname) except (KeyboardInterrupt, EOFError): print # newline return 2 # return quit signal if len(comment) == 0: # pass to next rv = 1 # next elif len(comment) > 1: # save as comment readline.add_history(comment) self.comment = comment rv = 1 # next elif comment == 'b': # go back one rv = -1 # previous elif comment == 'd': # get data print self.hist() , print ' '.join(cmd_output("ls -dl '%s'" % self.name).split()[:8]) , nlines = cmd_output("wc -l '%s'" % self.name)[1:].split() or ['?'] print '%s lines' % nlines[0] print ' '.join(cmd_output( "file '%s'" % self.name).split(':')[1:]).strip() print cmd_output("od -cN64 -An '%s'" % self.name) line_width = FileComment.cols - 5 tc = "cat -t '%s' | cut -c1-%d | head -6" % (self.name, line_width) if os.path.isdir(self.name): tc = "ls -l %s | head -6" % self.name print cmd_output(tc) elif comment == 'e': # erase existing comment self.comment = '' rv = 1 # next elif comment == 'l': # use less to paginate file subprocess.call(['less', self.name]) elif comment == 'm': # use less to paginate file subprocess.call(['man', self.name]) elif comment == 'q': # quit rv = 2 # quit signal elif comment == 'r': # delete cmd_output("rm -rf '%s'" % self.name) rv = 1 # next elif comment == 't': # cat print open(self.name).read().rstrip() elif comment == 'v': # open with vi subprocess.call(['vim', self.name]) else: print USAGE return rv
def init(cls): """Initialize a nice environment to run in """ import os cls.debug = os.getenv('PYTHONRC_DEBUG') if os.getenv('NOPYTHONRC'): # Not loading the python environment cls.dp( "Skipping loading the pythonrc environment stuff" ) return try: import readline except ImportError: readline = None cls.readline = readline if readline: # Set the history file cls.histfile = os.path.join( os.getenv('HOME', '.'), '.python_history' ) cls.dp( "Using history file '%s'" % cls.histfile ) # Read the history file if os.path.exists( cls.histfile ): readline.read_history_file(cls.histfile) cls.dp( "Using existing history information" ) else: cls.dp( "Creating new history file" ) # Set the number of history items to 3000 readline.set_history_length(3000) cls.dp( "History size set to 3000" ) # Put a marker for the starting time. readline.add_history("# starting %s" % cls.strtime() ) cls.dp( "Marked start of history file" ) # Allow Tab Completion import rlcompleter # This sets up python specific completion readline.parse_and_bind("tab: complete") cls.dp( "Started completion" ) else: cls.dp( "No readline available" ) # Set the prompts import sys sys.ps1 = "python%s> " % ".".join( map( str, sys.version_info[:2] ) ) sys.ps2 = " " * ( len( sys.ps1 ) - 2 ) + "> " cls.dp( "Set prompts" ) # The the exit function import atexit atexit.register(cls.exit) cls.dp( "Registered exit function" )