Python readline.insert_text() Examples

The following are 22 code examples of readline.insert_text(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module readline , or try the search function .
Example #1
Source File: rlcompleter.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #2
Source File: pythonrc.py    From pythonrc with MIT License 5 votes vote down vote up
def auto_indent_hook(self):
        """Hook called by readline between printing the prompt and
        starting to read input.
        """
        readline.insert_text(self._indent)
        readline.redisplay() 
Example #3
Source File: release.py    From eggnog-mapper with GNU Affero General Public License v3.0 5 votes vote down vote up
def ask(string, valid_values, default=-1, case_sensitive=False):
    """ Asks for a keyborad answer """

    v = None
    if not case_sensitive:
        valid_values = [value.lower() for value in valid_values]
    while v not in valid_values:
        readline.set_startup_hook(lambda: readline.insert_text(default))
        try:
            v = raw_input("%s [%s] " % (string, ', '.join(valid_values))).strip()
            if v == '' and default>=0:
                v = valid_values[default]
            if not case_sensitive:
                v = v.lower()
        finally:
            readline.set_startup_hook()
    return v 
Example #4
Source File: rlcompleter.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #5
Source File: pam.py    From python-pam with MIT License 5 votes vote down vote up
def input_with_prefill(prompt, text):
        def hook():
            readline.insert_text(text)
            readline.redisplay()
        readline.set_pre_input_hook(hook)

        if sys.version_info >= (3,):
            result = input(prompt)
        else:
            result = raw_input(prompt)

        readline.set_pre_input_hook()
        return result 
Example #6
Source File: rlcompleter.py    From Imogen with MIT License 5 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #7
Source File: rlcompleter.py    From scylla with Apache License 2.0 5 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #8
Source File: passhole.py    From passhole with GNU General Public License v3.0 5 votes vote down vote up
def editable_input(prompt, prefill=None):
    def hook():
        readline.insert_text(prefill)
        readline.redisplay()
    readline.set_pre_input_hook(hook)
    result = input(green(prompt + ': '))
    readline.set_pre_input_hook()
    return result 
Example #9
Source File: terminalkeyboard.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def edit_option(self, idx):
        # Go up
        sys.stdout.write('\033[1A' * (len(self.options) - idx))
        # Go left to the beginning of the line
        sys.stdout.write('\033[1D' * (max([len(x) for x in self.options]) + 3))
        sys.stdout.flush()
        prev_value = self.options[idx]
        readline.set_startup_hook(lambda: readline.insert_text(prev_value))
        try:
            new_value = input('E: ')
        finally:
            readline.set_startup_hook()

        self.options[idx] = new_value
        sys.stdout.write('\033[1A' * (idx + 1))
        sys.stdout.write('\033[1D' * (max([len(x) for x in self.options]) + 3))
        sys.stdout.flush()
        self.print_options()
        return prev_value, new_value 
Example #10
Source File: parse_functions.py    From todxpy with GNU General Public License v2.0 5 votes vote down vote up
def rlinput(prompt, prefill = ''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return input(prompt)
   finally:
      readline.set_startup_hook() 
Example #11
Source File: rlcompleter.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #12
Source File: sshmenu.py    From sshmenu with MIT License 5 votes vote down vote up
def input_prefill(prompt, text):
    def hook():
        readline.insert_text(text)
        readline.redisplay()

    readline.set_pre_input_hook(hook)
    result = input(prompt)
    readline.set_pre_input_hook()
    return result 
Example #13
Source File: switch_cfg.py    From power-up with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return input(prompt)
    finally:
        readline.set_startup_hook() 
Example #14
Source File: config_manager.py    From GPIOnext with MIT License 4 votes vote down vote up
def getInput( self, prompt, prefill='' ):

		readline.set_startup_hook(lambda: readline.insert_text('\n' + prefill))
		try:
			return input(prompt).replace('\n','')
		finally:
			readline.set_startup_hook() 
Example #15
Source File: smgr_add.py    From contrail-server-manager with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return raw_input(prompt)
    finally:
        readline.set_startup_hook() 
Example #16
Source File: configure_mgmt_switches.py    From power-up with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return input(prompt)
    finally:
        readline.set_startup_hook() 
Example #17
Source File: show_mgmt_switches.py    From power-up with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return input(prompt)
    finally:
        readline.set_startup_hook() 
Example #18
Source File: utilities.py    From power-up with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    log = logger.getlogger()
    log.debug(f"prompt='{repr(prompt)}' prefill='{prefill}'")
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        user_input = input(prompt)
        log.debug(f"user_input='{user_input}'")
        return user_input
    finally:
        readline.set_startup_hook() 
Example #19
Source File: show_status.py    From power-up with Apache License 2.0 4 votes vote down vote up
def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return input(prompt)
    finally:
        readline.set_startup_hook() 
Example #20
Source File: session.py    From mouse with GNU General Public License v3.0 4 votes vote down vote up
def tab_complete(self, text, state):
		try:
			is_double_tab = False
			current_text = readline.get_line_buffer()
			if self.last_tab and self.last_tab == current_text:
				is_double_tab = True
			self.last_tab = current_text

			# if no input do nothing
			if not current_text:
				return
			# get last input
			split_input = current_text.split()[-1]
			
			search_path = os.path.split(split_input)[0]
			search_text = os.path.split(split_input)[1]
			data = self.send_command({"cmd":"tab_complete","args":search_path if search_path else "."})
			results = json.loads(data)

			matched_keys = []
			if results:
				keys = results.keys()
				keys.sort()
				# append / if it is a directory				
				for k in keys:
					# continue if no match
					if k.startswith(search_text):
						matched_keys.append(k)

			# edge cases
			if not matched_keys:
				# don't do anything if we have no matches
				return
			elif len(matched_keys) == 1:
				# if there is only 1 match and that match is a directory, append a '/'
				readline.insert_text(matched_keys[0][len(search_text):])
				if matched_keys[0] in results:
					if results[matched_keys[0]] == 4 or results[matched_keys[0]] == 10:
						readline.insert_text("/")
				readline.redisplay()
				return
			elif not is_double_tab:
				# lcp of multiple matched
				find = h.find_longest_common_prefix(matched_keys)
				readline.insert_text(find[len(search_text):])
				readline.redisplay()
				return

			print("")
			for k in matched_keys:
				if results[k] == 4:
					print(h.COLOR_INFO + k + h.ENDC)
				elif results[k] == 10:
					print(h.COLOR_INFO + k + h.ENDC)
				else:
					print(k)
				# back to where we are
			sys.stdout.write(self.get_handle() + current_text)		
		except Exception as e:
			print("\n error - " + str(e)) 
Example #21
Source File: g1modules.py    From gluster-one with GNU General Public License v3.0 4 votes vote down vote up
def user_input(msg, initial=''):
    # Function to capture raw_input w/ key buffer flush
    tcflush(sys.stdin, TCIOFLUSH)
    readline.set_startup_hook(lambda: readline.insert_text(initial))
    keyin = raw_input(msg)
    return keyin 
Example #22
Source File: command.py    From ishell with MIT License 4 votes vote down vote up
def complete(self, line, buf, state, run=False, full_line=None):
        logger.debug('Walked to: %s' % self.name)
        if line and self.dynamic_args and len(line) > 1:
            logger.debug("Dynamic arg '%s' found" % line[0])
            has_arg_completed = True
            # Dynamic arg already filled, jump to next word
            next_command = line[1]
            line.pop(0)
        elif line:
            next_command = line[0]
            has_arg_completed = False

            candidates = self.get_candidates(next_command)
            if candidates and len(candidates) > 1 and buf:
                logger.debug("More than one candidate, not walking in %s" % buf)
                return self._next_command(state, buf)
            elif candidates and next_command in candidates:
                logger.debug("Found %s in childs, walking." % next_command)
                cmd = candidates.pop(next_command)
                return cmd.complete(line[1:], buf, state, run, full_line)
            else:
                logger.debug('Not walking because %s was not found in childs' % next_command)
                if has_arg_completed:
                    return self._next_command(state, next_command)

        logger.debug('Line=>%s, Buf=>%s, state=>%s' % (line, buf, state))

        if run:
            logger.debug('Executing %s' % self.name)
            return self.run(full_line.rstrip())

        logger.debug('Starting arg complete')

        # Checking if user already typed a valid arg without space at end
        if self.dynamic_args:
            if len(line) and buf and line[0] in self.args():
                readline.insert_text(" ")
                logger.debug("Inserted blank space")
            elif len(line) and not buf and line[0] not in self.args():
                logger.debug("Found an unknown arg, suggesting next command.")
                return self._next_command(state, buf)

        if buf == self.name:
            readline.insert_text(" ")
            logger.debug("Inserted blank space")

        if not self.dynamic_args:
            return self._next_command(state, buf)

        if self.dynamic_args:
            if (buf.strip() in self.args()):
                return self._next_command(state, buf)
            elif line and line[0] in self.args():
                return self._next_command(state, buf)
            else:
                return self._dynamic_args(state, buf)
        else:
            return self._next_command(state, buf)