def configure(self): while True: num_choices = 0 choices = [] for architecture in self.project.db.architectures: print(' %u. %s - %s' % (num_choices + 1, architecture.name, architecture.description)) choices.append(architecture) num_choices += 1 choice = input('choice[1-%u]: ' % num_choices) architecture = None try: choice = int(choice) if choice in range(1, num_choices + 1): architecture = choices[choice - 1] except: pass last = readline.get_current_history_length() readline.remove_history_item(last - 1) if architecture: break if not self.architecture: self.architecture = Architecture(architecture) self.architecture.configure(self.project) self.generate_config()
def configure(self): while True: source = self.source num_choices = 0 choices = [] print(' %s - %s' % (source.name, source.description)) for option in source.options: print(' %u. %s - %s' % (num_choices + 1, option.name, option.description)) choices.append(option) num_choices += 1 choice = input('choice[1-%u]: ' % num_choices) option = None try: choice = int(choice) if choice in range(1, num_choices + 1): option = choices[choice - 1] except: pass last = readline.get_current_history_length() readline.remove_history_item(last - 1) if option: break self.value = option
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 prompt_user(prompt, noblank=False, multiline=False): try: while True: if multiline: print(prompt) userinput = sys.stdin.read() else: try: # python 2 must call raw_input() because input() # also evaluates the user input and that causes # problems. userinput = raw_input('%s ' % prompt) except NameError: # python 3 replaced raw_input() with input()... # it no longer evaulates the user input. userinput = input('%s ' % prompt) if noblank: if userinput != '': break else: break except EOFError: print() return '' if userinput != '': last = readline.get_current_history_length() - 1 if last >= 0: readline.remove_history_item(last) return userinput
def readline(self, prompt=None, default=None, history=True, complete=True): old_completion = self.completion if not complete: self.disable_completion() prompt_suffix = '' if default: try: readline.set_pre_input_hook(self.hook) except AttributeError: prompt_suffix = ' [' + str(default) + ']' self.default = default if not prompt: prompt = self.prompt prompt += prompt_suffix if len(prompt) > 0: prompt += ' ' try: result = input(prompt) if not history and len(result) > 0: readline.remove_history_item( readline.get_current_history_length() - 1) finally: if default: try: readline.set_pre_input_hook(None) except AttributeError: pass if not complete and old_completion: self.enable_completion() return result
def lookupCb(thing): if not thing: self.stdout.write('No thing found for %s\n' % shortid.encode('utf-8')) return self.getRootCommand()._stdio.teardown() def pre_input_hook(): readline.insert_text(display.display( thing, shortid=False, colored=False)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None) readline.set_pre_input_hook(pre_input_hook) line = raw_input("GTD edit> ").decode('utf-8') # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based readline.remove_history_item(readline.get_current_history_length() - 1) self.getRootCommand()._stdio.setup() try: d = parse.parse(line) except ValueError, e: self.stderr.write('Could not parse line: %s\n' % log.getExceptionMessage(e)) return 3
def raw_input_no_history(self, prompt): if self.filelines: return self.filelines.pop(0) else: input = raw_input(prompt) readline.remove_history_item(readline.get_current_history_length() - 1) return input
def raw_input_no_history(prompt): """Removes user input from readline history.""" import readline input = raw_input(prompt) if input != '': readline.remove_history_item(readline.get_current_history_length() - 1) return input
def ask_question(question, allowed=None): """ Asks a yes/no question to the user """ readline = get_readline() if allowed is None: allowed = { 'y': True, 'Y': True, 'yes': True, 'n': False, 'N': False, 'no': False } while True: line = builtins.input(question) line = line.strip() # we don't want these to go into the history if readline is not None: try: l = readline.get_current_history_length() if l: readline.remove_history_item(l - 1) except: pass if line in allowed: return allowed[line]
def receive(self, _): # Remove the edit command from history readline.remove_history_item(readline.get_current_history_length() - 1) if self.n is None: self.n = readline.get_current_history_length() - 1 command = readline.get_history_item(self.n + 1) # 1-based assert command is not None with open(self.tmp_file, 'w') as output: output.write(command) edit_command = f'{self.editor} {self.tmp_file}' process = subprocess.Popen(edit_command, shell=True, executable='/bin/bash', universal_newlines=True) process.wait() with open(self.tmp_file, 'r') as input: command_lines = input.readlines() # Make sure that each new line after the first is preceded by a continuation string. continued_correctly = [] correct_termination = self.env().reader.continuation + '\n' for line in command_lines[:-1]: if not line.endswith(correct_termination): assert line[-1] == '\n', line line = line[:-1] + correct_termination continued_correctly.append(line) continued_correctly.append(command_lines[-1]) self.env().edited_command = ''.join(continued_correctly) os.remove(self.tmp_file)
def __delitem__(self, index): ''' Delete a history event at ``index``. ''' if hasattr(readline, 'remove_history_item'): index = self.normalize_index(index) readline.remove_history_item(index) # pylint: disable=no-member
def editLine(line, prompt="edit> ", echo=True): """Edit a line using readline @param prompt: change prompt @param echo: whether to echo user text or not""" _checkIsInteractive() if line: reinjectInRawInput(line) if len(_answers) > 0: line = _answers.pop(0) else: try: if echo: line = input(prompt) else: line = getpass(prompt) except EOFError: line = "" # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based if sys.platform != 'win32': length = readline.get_current_history_length() if length > 0: readline.remove_history_item(length - 1) return line
def raw_input_no_history(prompt): """Removes user input from readline history.""" import readline input = raw_input(prompt) if input != '': readline.remove_history_item(readline.get_current_history_length()-1) return input
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 _SaveHistory(self): """Save readline history then clear history.""" self._saved_history = [] for idx in xrange(1, readline.get_current_history_length()+1): self._saved_history.append(readline.get_history_item(idx)) for idx in xrange(readline.get_current_history_length()): readline.remove_history_item(0)
def ask_question(question, allowed=None): """ Asks a yes/no question to the user """ readline = get_readline() if allowed is None: allowed = { 'y': True, 'Y': True, 'yes': True, 'n': False, 'N': False, 'no': False } while True: line = raw_input(question) line = line.strip() # we don't want these to go into the history if readline is not None: try: l = readline.get_current_history_length() if l: readline.remove_history_item(l - 1) except: pass if line in allowed: return allowed[line]
def do_edit(self, id): """Interactively edit task given by #id.""" try: import readline except ImportError: print "Cannot edit without the 'readline' module!" return # Parse command line idx = self._parse_args(id)[0] if not idx: return task = self.todo.find('id', idx) if not task: return def pre_input_hook(): readline.insert_text(self._dump_line(task)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None) readline.set_pre_input_hook(pre_input_hook) line = raw_input("GTD edit> ") # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based readline.remove_history_item(readline.get_current_history_length() - 1) self._replace(idx, line)
def prompt_user(prompt, noblank=False, multiline=False): try: while True: if multiline: print(prompt) userinput = sys.stdin.read() else: try: # python 2 must call raw_input() because input() # also evaluates the user input and that causes # problems. userinput = raw_input('%s ' % prompt) except NameError: # python 3 replaced raw_input() with input()... # it no longer evaulates the user input. userinput = input('%s ' % prompt) if noblank: if userinput != '': break else: break except EOFError: print('') return '' if userinput != '': last = readline.get_current_history_length() - 1 if last >= 0: readline.remove_history_item(last) return userinput
def editLine(line, prompt="edit> ", echo=True): """Edit a line using readline @param prompt: change prompt @param echo: whether to echo user text or not""" if line: reinjectInRawInput(line) if len(_answers) > 0: line = _answers.pop(0) else: try: if echo: line = input(prompt) else: line = getpass(prompt) except EOFError: line = "" # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based if sys.platform != 'win32': length = readline.get_current_history_length() if length > 0: readline.remove_history_item(length - 1) return line
def ask_question(question, allowed=None): ''' Asks a yes/no question to the user ''' if allowed is None: allowed = { 'y': True, 'Y': True, 'yes': True, 'n': False, 'N': False, 'no': False } while True: line = raw_input(question) line = line.strip() # we don't want these to go into the history if use_readline: try: L = readline.get_current_history_length() # @UndefinedVariable if L: readline.remove_history_item(L - 1) # @UndefinedVariable except: pass if line in allowed: return allowed[line]
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 silent_invariant_raw_input(prompt,comp=None,wipe=False, echo = True,color = Colors.NONE,completion=None): prompt = color+prompt+Colors.ENDC if not Control.silent: readline.set_startup_hook(lambda: readline.insert_text(comp)) if completion=="Files": readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(fileCompleter) elif not completion is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(lambda a,b:listCompleter(a,b,completion)) try: if Control.silent: prompt = "" if echo: ret = raw_input(prompt) else: ret = getpass.getpass(prompt) wipe = False if wipe: l = readline.get_current_history_length() if l > 0: readline.remove_history_item(l-1) return ret finally: if not Control.silent: readline.set_startup_hook() if not completion is None: readline.parse_and_bind("set disable-completion On") readline.set_completer(None) #readline.parse_and_bind("tab: \t") readline.set_completer_delims("")
def raw_input_no_history(output=None): input = raw_input(output) readline.remove_history_item(readline.get_current_history_length()-1) return input
def textInput(title, insert=None): if insert: title = "%s [%s]:" % (title, insert,) result = raw_input(title) if readline.get_current_history_length(): readline.remove_history_item(readline.get_current_history_length() - 1) if not result: result = insert return result
def _recursivePromptEntry(self, labels, array, level=0): for i in range(len(labels)): if self.broken == True: break if type(labels[i]) is str: # Allow for printing auto-complete suggestions or skipping entry of elements (customizing prompt requires more args) stillDoPrompt = self.prePromptHook(labels[i], array) if stillDoPrompt == True: # Generic promptStr promptStr = " " * level + "%s: " % labels[i] # Will it be possible to validate response? # Catch KeyboardInterrupt to all the user to exit the entry process try: response = raw_input(promptStr) # Allow correction of response or insertion of default value of current or previously skipped field stillAppendResponse = self.postPromptHook( labels[i], array, response) if stillAppendResponse == True: array.append(response) else: # post prompt hook must have appended to the array pass print "array = ", array # Remove entry items from command history if response != '': pos = readline.get_current_history_length() - 1 readline.remove_history_item(pos) except KeyboardInterrupt: self.broken = True print "" print "Aborting..." break else: # pre prompt hook must have appended to the array, or let it be handled by post prompt hook continue elif type(labels[i]) is dict: array.append([]) # by design dictionary will only have one key key = labels[i].keys()[0] print " " * level + "[%s]" % key self._recursivePromptEntry(labels[i][key], array[i], level + 1) else: print "--> Unhandled prompt entry type: ", type(labels[i]) if level == 0: #!print array #!self.recursivePrintEntries(self.xmlEntryDef, array) pass
def raw_input_no_history(self, prompt): if self.filelines: return self.filelines.pop(0) else: input = raw_input(prompt) readline.remove_history_item( readline.get_current_history_length() - 1 ) return input
def clean_and_save_history(history): import readline commands = set() for commandId in xrange(readline.get_current_history_length(), 0, -1): command = readline.get_history_item(commandId) if command in commands: readline.remove_history_item(commandId - 1) else: commands.add(command) readline.write_history_file(history)
def remove_history_items(num): """ Call after the input to be removed. """ try: for i in range(num): readline.remove_history_item( readline.get_current_history_length() - 1) except ValueError: return
def write_history(self, trim_last=False): if not HAS_READLINE or history_file is None: return try: readline.set_history_length(self.maxhist) if trim_last: n = readline.get_current_history_length() readline.remove_history_item(n-1) readline.write_history_file(history_file) except: print("Warning: could not write history file")
def input(self, prompt=''): "Prompts and reads input from the user" lines = self.wrap(prompt, newline=False).split('\n') prompt = lines[-1] s = ''.join(line + '\n' for line in lines[:-1]) self.stdout.write(s) result = input(prompt).strip() # Strip the history from readline (we only want commands in the # history) readline.remove_history_item(readline.get_current_history_length() - 1) return result
def __cmd_login__(self, username = u"", exchange = u"mtgox"): u"Set login credentials. Exchange can be either mtgox or exchb." if not username: while not username: username = raw_input(u"Username: "******"" while not password: password = getpass.getpass() self.__mtgox.set_credentials(exchange, username, password) self.__mtgox_commission = self.__mtgox.get_commission()
def write_history(self, trim_last=False): if not HAS_READLINE or history_file is None: return try: readline.set_history_length(self.maxhist) if trim_last: n = readline.get_current_history_length() readline.remove_history_item(n - 1) readline.write_history_file(history_file) except: print("Warning: could not write history file")
def _check_history_duplicates(value): # prevent duplicates in histtory the last ten lines # of the history - if the item is already there - # remove it again histlen = readline.get_current_history_length() if histlen > 1: for i in range(max(histlen - 10, 0), histlen): previtem = readline.get_history_item(i) if previtem == value: lg.debug("removing duplicate %s" % value) readline.remove_history_item(histlen - 1) break
def compact_history(): if hasattr(readline, "replace_history_item"): unique_history = utils.unique_list() for index in reversed(list(range(1, readline.get_current_history_length()))): hist_item = readline.get_history_item(index) if hist_item: # some history items are None (usually at index 0) unique_history.append(readline.get_history_item(index)) unique_history.reverse() for index in range(len(unique_history)): readline.replace_history_item(index + 1, unique_history[index]) for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))): readline.remove_history_item(index)
def loop(self): previous_completer = readline.get_completer() readline.parse_and_bind("tab: complete") readline.parse_and_bind('?: "--help^\n"') readline.set_completer(self.walk) prompt = self.prompt + self.prompt_delim if not ishell._current_prompt: previous_prompt = prompt else: previous_prompt = ishell._current_prompt ishell._current_prompt = prompt previous_command = "" while 1: try: sys.stdout.write("\r") if self._exit: break sys.stdout.write("\033[K") readline.set_startup_hook( lambda: readline.insert_text(previous_command)) input_ = input(prompt + " ") readline.set_startup_hook() if len(str(input_)) >= 7 and input_[-7:] == "--help^": sys.stdout.write('\x1b[1A') sys.stdout.write('\x1b[2K') input_ = input_[:-7] + "?" previous_command = input_[0:-1] history_len = readline.get_current_history_length() readline.remove_history_item(history_len - 1) if len(str(input_)) > 1 and input_[-2] != " ": previous_command += "?" continue else: readline.add_history(previous_command + "?") print(prompt + " " + previous_command + "?") else: previous_command = "" if not input_.strip(): self.print_childs_help() elif input_ in ('quit', 'exit'): break else: self.walk_and_run(input_) except (KeyboardInterrupt, EOFError): print("exit") break except Exception: print(traceback.format_exc()) sys.exit(1) ishell._current_prompt = previous_prompt readline.set_completer(previous_completer)
def textInput(title, insert=None): if insert: title = "%s [%s]:" % ( title, insert, ) result = raw_input(title) if readline.get_current_history_length(): readline.remove_history_item(readline.get_current_history_length() - 1) if not result: result = insert return result
def multiline(self, firstline=''): full_input = [] # keep a list of the entries that we've made in history old_hist = [] if 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': print break full_input.append(line) if ';' in line: break # add the final readline history position if hasReadline: old_hist.append(readline.get_current_history_length()) cmd = ' '.join(full_input) 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) return cmd
def __cmd_login__(self, username=u""): u"Set login credentials." if not username: while not username: username = raw_input(u"Username: "******"" while not password: password = getpass.getpass() self.__mtgox.set_credentials(username, password)
def delete_python_history(self, command: str) -> None: # pylint: disable=no-self-use readline_history = [ readline.get_history_item(i + 1) for i in range(readline.get_current_history_length()) ] cmd_indexes = [ i for i, cmd in enumerate(readline_history) if cmd == command ] for cmd_idx in reversed(cmd_indexes): readline.remove_history_item(cmd_idx) readline.write_history_file(str(SHELLS[Shell.STANDARD]["hist"]))
def singleline(self, store_in_history=True, **kwargs): """Reads a single line of input. The store_in_history kwarg flags whether the input should be stored in readline's in-memory history. """ if not store_in_history: # store current position to remove it later try: import readline except ImportError: store_in_history = True pos = readline.get_current_history_length() - 1 rtn = input(self.prompt) if not store_in_history and pos >= 0: readline.remove_history_item(pos) return rtn
def input_function(prompt="", history=True): """Reads an input line, with readline disabled""" remove_history = rlmodule is not None and not history if remove_history: hcurlen = rlmodule.get_current_history_length() hmaxlen = rlmodule.get_history_length() rlmodule.set_history_length(hmaxlen + 1) try: answer = input(prompt) # pylint: disable=bad-builtin finally: if remove_history: hlen = rlmodule.get_current_history_length() for i in range(hcurlen, hlen): rlmodule.remove_history_item(i) rlmodule.set_history_length(hmaxlen) return answer
def run(shell): """ Run the shell until the exit command is called Input: - shell: a shell object that will be run """ set_history_length(2000) try: read_history_file(Shell.history_file) except FileNotFoundError: open(Shell.history_file, "w+").close() except PermissionError: pass while not shell.exit: try: # Read user input user_input = read_user_input() if user_input: remove_history_item(get_current_history_length() - 1) else: continue token_list, list_of_char = get_token_list(user_input) # Add final input string after get_history_item input_string = "".join(list_of_char) if (get_history_item(get_current_history_length()) != input_string and input_string): add_history(input_string) print(" ".join([str(item) for item in token_list])) # print("\n".join([str(item) for item in token_list])) # print("".join([item.original_string for item in token_list])) command_list = get_command_list(token_list) if not command_list: continue expand_token_for_command_list(command_list, shell) # print(command_list) # print([item.argument_list for item in command_list]) except EOFError: return except BadSubstitutionError as e: print("intek-sh: %s: bad substitution" % e.argument) except UnexpectedTokenError as e: print("intek-sh: Unexpected token after %s" % e.argument) except CommandNotFoundError as e: print("intek-sh: %s: command not found" % e.argument) except EventNotFoundError as e: print("intek-sh: %s: event not found" % e.argument)
def execute(self, cmdname, options): opts, args = getopt.getopt(shlex.split(options), 'n') doURLDecode = False for name, _ignore_value in opts: if name == "-n": doURLDecode = True else: print "Unknown option: %s" % (name, ) print self.usage(cmdname) raise WrongOptions if len(args) != 2: print "Wrong number of arguments: %d" % (len(args), ) print self.usage(cmdname) raise WrongOptions while True: result = raw_input("Really move resource '%s' to '%s' [y/n]: " % ( args[0], args[1], )) if readline.get_current_history_length(): readline.remove_history_item( readline.get_current_history_length() - 1) if not result: continue if result[0] == "n": return True elif result[0] == "y": break fromResource = args[0] if not fromResource.startswith("/"): fromResource = os.path.join(self.shell.wd, fromResource) toResource = args[1] if not toResource.startswith("/"): toResource = os.path.join(self.shell.wd, toResource) resourceFrom = URL(url=fromResource, decode=doURLDecode) resourceTo = URL(url=self.shell.server + toResource, decode=doURLDecode) self.shell.account.session.moveResource(resourceFrom, resourceTo) return True
def execute(self, cmdname, options): opts, args = getopt.getopt(shlex.split(options), 'n') doURLDecode = False for name, _ignore_value in opts: if name == "-n": doURLDecode = True else: print "Unknown option: %s" % (name,) print self.usage(cmdname) raise WrongOptions if len(args) != 2: print "Wrong number of arguments: %d" % (len(args),) print self.usage(cmdname) raise WrongOptions while True: result = raw_input("Really move resource '%s' to '%s' [y/n]: " % (args[0], args[1],)) if readline.get_current_history_length(): readline.remove_history_item(readline.get_current_history_length() - 1) if not result: continue if result[0] == "n": return True elif result[0] == "y": break fromResource = args[0] if not fromResource.startswith("/"): fromResource = os.path.join(self.shell.wd, fromResource) toResource = args[1] if not toResource.startswith("/"): toResource = os.path.join(self.shell.wd, toResource) resourceFrom = URL(url=fromResource, decode=doURLDecode) resourceTo = URL(url=self.shell.server + toResource, decode=doURLDecode) self.shell.account.session.moveResource(resourceFrom, resourceTo) return True
def execute_command(self, ged_function, *args, **kwargs): args = list(args) command_name = kwargs.get("command_name", ged_function.__name__) args.insert(0, command_name) if readline: history_index = readline.get_current_history_length() while True: cmd_args = cta.ctypes_string_array(args) result = ged_function(self._ged_pointer, len(cmd_args), cmd_args) # if result != libged.GED_OK: # print "Result: <", result, ">" if not (result & libged.GED_MORE): break prompt = self._ged_pointer.contents.ged_result_str.contents.vls_str new_input = raw_input(prompt) args.extend(new_input.split()) if readline: # this code collapses the multiple history items resulting from # the "raw_input" calls to a single history item (same behavior as mged) new_history_index = readline.get_current_history_length() if new_history_index > history_index: command_pattern = re.compile("^(.*)\([^)]*\)\s*") command_matcher = command_pattern.search(readline.get_history_item(history_index)) if command_matcher: history_command = command_matcher.group(1) else: history_command = ged_function.__name__ crt_index = readline.get_current_history_length() while crt_index > history_index: readline.remove_history_item(history_index) crt_index = readline.get_current_history_length() cmd_line = "{}(\"{}\")".format( history_command, "\", \"".join(args[1:]) ) readline.add_history(cmd_line) if result & libged.GED_QUIET: ged_output = None else: ged_output = self._ged_pointer.contents.ged_result_str.contents.vls_str if ged_output: print ged_output return result
def execute_command(self, ged_function, *args, **kwargs): args = list(args) command_name = kwargs.get("command_name", ged_function.__name__) args.insert(0, command_name) if readline: history_index = readline.get_current_history_length() while True: cmd_args = cta.ctypes_string_array(args) result = ged_function(self._ged_pointer, len(cmd_args), cmd_args) # if result != libged.GED_OK: # print "Result: <", result, ">" if not (result & libged.GED_MORE): break prompt = self._ged_pointer.contents.ged_result_str.contents.vls_str new_input = raw_input(prompt) args.extend(new_input.split()) if readline: # this code collapses the multiple history items resulting from # the "raw_input" calls to a single history item (same behavior as mged) new_history_index = readline.get_current_history_length() if new_history_index > history_index: command_pattern = re.compile("^(.*)\([^)]*\)\s*") command_matcher = command_pattern.search( readline.get_history_item(history_index)) if command_matcher: history_command = command_matcher.group(1) else: history_command = ged_function.__name__ crt_index = readline.get_current_history_length() while crt_index > history_index: readline.remove_history_item(history_index) crt_index = readline.get_current_history_length() cmd_line = "{}(\"{}\")".format(history_command, "\", \"".join(args[1:])) readline.add_history(cmd_line) if result & libged.GED_QUIET: ged_output = None else: ged_output = self._ged_pointer.contents.ged_result_str.contents.vls_str if ged_output: print ged_output return result
def do_help_briefly(self, **args): """show the list of command helps""" line = self.onecmd_line words = self.onecmd_words # print(line, words) if line[-1] == ' ': targetwords = words[1:] lastword = '' else: # incomplete targetwords = words[1:-1] lastword = words[-1] cur_index, cur_node = self.cmdtree.find(targetwords, bestmatch=True) keys = [ key for key in cur_node if key.startswith(lastword) and key not in COMPLETE_IGNORES ] if keys: if cur_node.eoc: keys.append("<cr>") max_len = max(map(len, keys), default=12) hstr = '{0:<%s} {1}\n' % (max_len) strlist = list() for key in keys: try: strlist.append(hstr.format(key, cur_node[key].__doc__)) except KeyError: strlist.append(hstr.format(key, cur_node.__doc__)) self.pprint(strlist) strlist = list() self.indent_for_brief = ' ' * (max_len + 4) self.do_help() self.pprint(strlist) else: if cur_node.eoc: self.do_help() self.line = line.replace(LIST, "") self.line = line.replace(BRIEF_HELP, "") self.line = self.line.lstrip() if not IS_WINDOWS: pos = readline.get_current_history_length() readline.remove_history_item(pos - 1)
def again(adv): """Repeat last command. The actual repeating is in execute(), it digs here in readline's history. Args: adv: namedtuple holding the game data Modifies: adv: player's actual command ('again') is substituted with the command before or with an empty string, if there wasn't any before (won't be recognized by the parser) Returns: string: message about repeating a certain command """ idx = readline.get_current_history_length() if idx > 1: readline.remove_history_item(idx - 1) adv.player["command"] = readline.get_history_item(idx - 1) else: adv.player["command"] = "" return adv.messages["repeat"] + adv.player["command"]
def remove_items(self, n=1): """Remove items from current session's in-memory history.""" if n <= 0: return try: import readline except ImportError: # Windows doesn't have readline, so gracefully ignore. return current_history_length = readline.get_current_history_length() if current_history_length - n >= self._initial_history_length: for _ in range(n): # pop n items from history list readline.remove_history_item( readline.get_current_history_length() - 1) else: raise Exception( f"Requested history item removal is not in current session history range. " f"({self._initial_history_length}, {current_history_length})")
def do_history(self, argv): """Command line history SYNOPSIS: history history <[COUNT]> DESCRIPTION: Returns a formatted string giving the event number and contents for each of the events in the history list except for current event. If [COUNT] is specified, only the [COUNT] most recent events are displayed. > history 10 - Display last 10 commands of the history. > history - Display the full history of events. """ import readline argv.append('9999999999') try: count = int(argv[1]) except: return self.interpret("help history") last = readline.get_current_history_length() while last > core.MAX_HISTORY_SIZE: readline.remove_history_item(0) last -= 1 first = last - count if first < 1: first = 1 for i in range(first, last): cmd = readline.get_history_item(i) print("{:4d} {:s}".format(i, cmd))
def testHistoryUpdates(self): readline.clear_history() readline.add_history("first line") readline.add_history("second line") self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "first line") self.assertEqual(readline.get_history_item(2), "second line") readline.replace_history_item(0, "replaced line") self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "replaced line") self.assertEqual(readline.get_history_item(2), "second line") self.assertEqual(readline.get_current_history_length(), 2) readline.remove_history_item(0) self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "second line") self.assertEqual(readline.get_current_history_length(), 1)
def editLine(line, prompt="edit> "): """Edit a line using readline""" if line: reinjectInRawInput(line) if len(_answers) > 0: line = _answers.pop(0) else: try: line = raw_input(prompt) except EOFError: line="" # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based if sys.platform != 'win32': length = readline.get_current_history_length() if length > 0: readline.remove_history_item(length - 1) return line.decode(ENCODING)
def do_edit(self, id): """Interactively edit task given by #id: GTD> edit #id GTD edit> My task to edit. @context p:Project""" try: import readline except ImportError: print "Cannot edit without the 'readline' module!" return # Parse command line idx = self._parse_args(id)[0] if not idx: return task = self.todo.find('id', idx) if not task: return def pre_input_hook(): readline.insert_text(self._dump_line(task)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None) readline.set_pre_input_hook(pre_input_hook) line = raw_input("GTD edit> ") # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based readline.remove_history_item(readline.get_current_history_length() - 1) self._replace(idx, line) print "Task #%d updated" % idx
def execute(self, cmdname, options): opts, args = getopt.getopt(shlex.split(options), '') for name, _ignore_value in opts: print "Unknown option: %s" % (name,) print self.usage(cmdname) raise WrongOptions paths = [] if len(args) == 0: print "Wrong number of arguments: %d" % (len(args),) print self.usage(cmdname) raise WrongOptions while True: result = raw_input("Really delete %d resource(s) [y/n]: " % (len(args),)) if readline.get_current_history_length(): readline.remove_history_item(readline.get_current_history_length() - 1) if not result: continue if result[0] == "n": return True elif result[0] == "y": break for arg in args: path = arg if not path.startswith("/"): path = os.path.join(self.shell.wd, path) paths.append(path) resource = URL(url=path) self.shell.account.session.deleteResource(resource) return True