Python readline.set_completer_delims() Examples

The following are 30 code examples of readline.set_completer_delims(). 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: armory_interactive.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def show_menu(CommandClass, CompleterClass, name):
    command = CommandClass(name)
    completer = CompleterClass(command)
    readline.set_completer(completer.complete)
    readline.set_completer_delims(" ")
    readline.parse_and_bind("tab: complete")

    res = False
    while res is not True:
        valid_commands = command.cmd.keys()

        ret_cmd = six.input("%s> " % name).strip()
        cmd, options = (ret_cmd.split(" ")[0], " ".join(ret_cmd.split(" ")[1:]))
        if cmd == "debug":
            pdb.set_trace()

        elif cmd.lower() in valid_commands:
            res = command.run_cmd(cmd, options)

        else:
            print("Invalid command.")

        readline.set_completer(completer.complete) 
Example #2
Source File: ipy_completer.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def h5py_item_completer(context, command):
    """Compute possible item matches for dict-like objects"""

    base, item = re_item_match.split(command)[1:4:2]

    try:
        obj = _retrieve_obj(base, context)
    except Exception:
        return []

    path, _ = posixpath.split(item)

    try:
        if path:
            items = (posixpath.join(path, name) for name in obj[path].keys())
        else:
            items = obj.keys()
    except AttributeError:
        return []

    items = list(items)
    readline.set_completer_delims(' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?')

    return [i for i in items if i[:len(item)] == item] 
Example #3
Source File: utils.py    From QRLJacking with GNU General Public License v3.0 6 votes vote down vote up
def Input_completer(keywords):
    completer = MyCompleter(keywords)
    readline.set_completer(completer.complete)
    if "libedit" in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind('tab: complete')
        #readline.parse_and_bind('"\\e[A": complete') # Up arrow
    readline.parse_and_bind("set colored-completion-prefix on")
    readline.parse_and_bind("set show-all-if-unmodified on")
    readline.parse_and_bind("set horizontal-scroll-mode on")
    if os.path.exists(history_file):
        readline.read_history_file(history_file)
        readline.set_history_length(20)
    readline.set_completer_delims(' ')
    atexit.register(save_history) 
Example #4
Source File: interpreter.py    From isf with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example #5
Source File: BaseInterpreter.py    From Industrial-Security-Auditing-Framework with GNU General Public License v3.0 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example #6
Source File: readline-complete-subcommand.py    From code-for-blog with The Unlicense 6 votes vote down vote up
def main():
    commands = {
        'file': {},
        'eat': {'breakfast', 'dinner', 'lunch', 'snack'},
        'play': {'cards', 'chess', 'go'},
        'walk': {'left', 'right', 'straight'},
    }
    readline.parse_and_bind('tab: complete')
    readline.set_completer(make_subcommand_completer(commands))

    # Use the default readline completer delims; Python's readline adds '-'
    # which makes filename completion funky (for files that contain '-').
    readline.set_completer_delims(" \t\n\"\\'`@$><=;|&{(")

    try:
        while True:
            s = input('>> ').strip()
            print('[{0}]'.format(s))
    except (EOFError, KeyboardInterrupt) as e:
        print('\nShutting down...') 
Example #7
Source File: cli.py    From clonedigger with GNU General Public License v3.0 6 votes vote down vote up
def init_readline(complete_method, histfile=None):
    """init the readline library if available"""
    try:
        import readline
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete_method)
        string = readline.get_completer_delims().replace(':', '')
        readline.set_completer_delims(string)
        if histfile is not None:
            try:
                readline.read_history_file(histfile)
            except IOError:
                pass
            import atexit
            atexit.register(readline.write_history_file, histfile)
    except:
        print('readline si not available :-(') 
Example #8
Source File: _rlcompleter.py    From magic-wormhole with MIT License 6 votes vote down vote up
def _input_code_with_completion(prompt, input_helper, reactor):
    # reminder: this all occurs in a separate thread. All calls to input_helper
    # must go through blockingCallFromThread()
    c = CodeInputter(input_helper, reactor)
    if readline is not None:
        if readline.__doc__ and "libedit" in readline.__doc__:
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")
        readline.set_completer(c.completer)
        readline.set_completer_delims("")
        debug("==== readline-based completion is prepared")
    else:
        debug("==== unable to import readline, disabling completion")
    code = input(prompt)
    # Code is str(bytes) on py2, and str(unicode) on py3. We want unicode.
    if isinstance(code, bytes):
        code = code.decode("utf-8")
    c.finish(code)
    return c.used_completion 
Example #9
Source File: featherduster.py    From featherduster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self, line):
      ishellCompleter = readline.get_completer()
      readline.set_completer_delims(' \t\n;')
      readline.parse_and_bind("tab: complete")
      readline.set_completer(completer.complete)

      sample_file = raw_input('Please enter the filename you want to open: ')
      try:
         sample_fh = open(sample_file,'r')
         feathermodules.samples.append(sample_fh.read())
         sample_fh.close()
         feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
      except:
         print 'Something went wrong. Sorry! Please try again.'
      finally:
         readline.set_completer(ishellCompleter) 
Example #10
Source File: featherduster.py    From featherduster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self, line):
      ishellCompleter = readline.get_completer()
      readline.set_completer_delims(' \t\n;')
      readline.parse_and_bind("tab: complete")
      readline.set_completer(completer.complete)

      sample_file = raw_input('Please enter the filename you want to open: ')
      try:
         sample_fh = open(sample_file,'r')
         feathermodules.samples.extend([sample.strip() for sample in sample_fh.readlines()])
         sample_fh.close()
         feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
      except:
         print 'Something went wrong. Sorry! Please try again.'
      finally:
         readline.set_completer(ishellCompleter) 
Example #11
Source File: barq.py    From barq with MIT License 6 votes vote down vote up
def training_loop():
    """
    The menu handler loop for the training menu. Reads commands and send them to the processor, otherwise shows the menu prompt.
    :return: None
    """
    try:
        command = ''
        while command == '':
            try:
                readline.set_completer_delims(' \t\n;')
                readline.parse_and_bind("tab: complete")
                readline.set_completer(trainingcomplete)
                command = raw_input(
                    'barq ' + color('training', 'yellow') + ' > ')
            except Exception as e:
                print(e)
            #command = prompt.query('aws sheller training > ', validators=[])
        command = str(command)
        process_training_command(command)
    except KeyboardInterrupt as k:
        print("CTRL C clicked in training")
        menu_backward() 
Example #12
Source File: barq.py    From barq with MIT License 6 votes vote down vote up
def instances_loop():
    """
    The command handler loop for the EC2 instances menu. Commands will be sent to the processor and the prompt will be displayed.
    :return: None
    """
    try:
        command = ''
        while command == '':
            try:
                readline.set_completer_delims(' \t\n;')
                readline.parse_and_bind("tab: complete")
                readline.set_completer(instancecomplete)
                command = raw_input('barq '+color('instances', 'blue')+' > ')
            except Exception as e:
                print(e)
        command = str(command)
        process_instances_command(command)
    except KeyboardInterrupt as k:
        print("CTRL+C pressed.")
        choice = prompt.query(color(
            "Are you sure you want to go back to the main menu? Y/N", 'red'), default='Y')
        if choice == 'Y':
            menu_backward()
        else:
            instances_loop() 
Example #13
Source File: barq.py    From barq with MIT License 6 votes vote down vote up
def main_loop():
    """
    The command handler loop for the main menu. Commands will be sent to the processor and the prompt will be displayed.
    :return: None
    """
    try:
        command = ''
        while command == '':
            try:
                readline.set_completer_delims(' \t\n;')
                readline.parse_and_bind("tab: complete")
                readline.set_completer(maincomplete)
                command = raw_input('barq '+color('main', 'green')+' > ')
            except Exception as e:
                exit()
            #command = prompt.query('aws sheller main> ', validators=[])
        command = str(command)
        process_main_command(command)
    except KeyboardInterrupt as k:
        print(color("CTRL+C pressed. Exiting...", 'red'))
        exit() 
Example #14
Source File: pan.py    From PAN_OCR with MIT License 6 votes vote down vote up
def init_tabComplete(self):
		''' Initializes the tab completer '''
		try:
			if OS_VERSION == "posix":
				global tabCompleter
				global readline
				from utils.PythonCompleter import tabCompleter
				import readline
				comp = tabCompleter()
				# we want to treat '/' as part of a word, so override the delimiters
				readline.set_completer_delims(' \t\n;')
				readline.parse_and_bind("tab: complete")
				readline.set_completer(comp.pathCompleter)
				if not comp:
					return -1
			return 0
		except:
			return -1 
Example #15
Source File: util.py    From rl-benchmark with Apache License 2.0 6 votes vote down vote up
def ask_list(label, items, alt=None, default=None):
    completer = AutoCompleter(items)
    readline.set_completer(completer.complete)
    readline.set_completer_delims('')
    readline.parse_and_bind('tab: complete')

    item = None
    while not item:
        item = ask_string(label, default=default)
        if item not in items:
            if alt and item in alt:
                item = items[alt.index(item)]
            else:
                print("Invalid entry (try pressing TAB)")
                item = None

    readline.set_completer(None)
    return item 
Example #16
Source File: ipy_completer.py    From keras-lambda with MIT License 6 votes vote down vote up
def h5py_item_completer(context, command):
    """Compute possible item matches for dict-like objects"""

    base, item = re_item_match.split(command)[1:4:2]

    try:
        obj = _retrieve_obj(base, context)
    except Exception:
        return []

    path, _ = posixpath.split(item)

    try:
        if path:
            items = (posixpath.join(path, name) for name in obj[path].keys())
        else:
            items = obj.keys()
    except AttributeError:
        return []

    items = list(items)
    readline.set_completer_delims(' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?')

    return [i for i in items if i[:len(item)] == item] 
Example #17
Source File: shell.py    From koadic with Apache License 2.0 6 votes vote down vote up
def get_command(self, prompt, auto_complete_fn=None, basefile_fn=None):
        try:
            if auto_complete_fn != None:
                import readline
                readline.set_completer_delims(' \t\n;/')
                readline.parse_and_bind("tab: complete")
                readline.set_completer(auto_complete_fn)
                # readline.set_completion_display_matches_hook(basefile_fn)
        except:
            pass

        # python3 changes raw input name
        if sys.version_info[0] == 3:
            raw_input = input
        else:
            raw_input = __builtins__['raw_input']

        cmd = raw_input("%s" % prompt)
        return cmd.strip() 
Example #18
Source File: Interface.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def use(self,args,pointer = None):
		global POINTER
		if(len(args) < 2):
			return None
		POINTER = args[1]
		moduleName = args[1].split('/')
		comp 	= Completer()
		readline.set_completer_delims(' \t\n;')
		readline.parse_and_bind("tab: complete")
		readline.set_completer(comp.complete)
		while True:
			input	= raw_input('SMOD ' + moduleName[0] + '(' + bcolors.OKBLUE + moduleName[-1] + bcolors.ENDC + ') >').strip().split()
			try:			
				result 	= getattr(globals()['Command'](),input[0])(input,args[1])
			except:
				return None
			if (POINTER == None):
				break 
Example #19
Source File: config.py    From ansible-inventory with GNU General Public License v3.0 5 votes vote down vote up
def __check_requirements( self ):
    if not os.path.exists( self.config_home ):
      os.mkdir( self.config_home )

    if not os.path.exists( self.config_file ):
      with open( self.config_file, 'w' ) as cf:
        cf.write( self.default_config )
        cf.close()

    if not os.path.exists( self.history_file ):
      open( self.history_file, 'a' ).close()
    readline.read_history_file( self.history_file )
    readline.set_completer_delims(' ')
# ) 
Example #20
Source File: rtsp.py    From rtsp with MIT License 5 votes vote down vote up
def input_cmd():
    readline.set_completer_delims(' \t\n')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    cmd = raw_input(COLOR_STR('Input Command # ',CYAN))
    PRINT('') # add one line
    return cmd
#----------------------------------------------------------------------- 
Example #21
Source File: cli.py    From zstack-utility with Apache License 2.0 5 votes vote down vote up
def __init__(self, options):
        self.options = options
        self.agent_ip = options.ip
        self.agent_port = options.port
        self.cip = options.cip

        self.http_server = http.HttpServer(port=10086)
        self.http_server.register_sync_uri('/result', self.callback)
        self.http_server.start_in_thread()
        print ""

        comp = Completer()
        readline.set_completer_delims(' \t\n;')
        readline.set_completer(comp.complete)
        readline.parse_and_bind("tab: complete") 
Example #22
Source File: readline_ui.py    From keras-lambda with MIT License 5 votes vote down vote up
def _init_input(self):
    readline.parse_and_bind("set editing-mode emacs")

    # Disable default readline delimiter in order to receive the full text
    # (not just the last word) in the completer.
    readline.set_completer_delims("\n")
    readline.set_completer(self._readline_complete)
    readline.parse_and_bind("tab: complete")

    # For Python 2-3 compatibility.
    try:
      self._input = raw_input
    except NameError:
      self._input = input 
Example #23
Source File: readline_ui.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def _init_input(self):
    readline.parse_and_bind("set editing-mode emacs")

    # Disable default readline delimiter in order to receive the full text
    # (not just the last word) in the completer.
    readline.set_completer_delims("\n")
    readline.set_completer(self._readline_complete)
    readline.parse_and_bind("tab: complete")

    # For Python 2-3 compatibility.
    try:
      self._input = raw_input
    except NameError:
      self._input = input 
Example #24
Source File: shell.py    From BoomER with GNU General Public License v3.0 5 votes vote down vote up
def initial(self):
        self.completer = MyCompleter.getInstance(self._options_start.keys(), self)
        readline.set_history_length(50)  # max 50
        readline.set_completer_delims(' \t\n;')  # override the delims (we want /)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.completer.complete)
        self.open_sessions = Session.getInstance() 
Example #25
Source File: PupyCmd.py    From backdoorme with MIT License 5 votes vote down vote up
def init_completer(self):
		readline.set_pre_input_hook(self.pre_input_hook)
		readline.set_completer_delims(" \t") 
Example #26
Source File: powerstager.py    From powerstager with MIT License 5 votes vote down vote up
def __init__(self, lhost, lport):
		self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.lhost = lhost
		self.lport = lport
		self.framework = Framework(self.send_command, self.check_command, self.get_response)
		self.command_definition = {}
		self.credentials = []
		self.fast_load = False
		self.prompt = ""
		self.os_target = None
		
		# Define command behavior
		self.command_definition["Local-Invoke"] 				= lambda x: self.psh_Local_Invoke(x[len("Local-Invoke"):].strip())
		self.command_definition["Local-Import-Module"] 			= lambda x: self.psh_Local_Invoke(x[len("Local-Import-Module"):].strip(), True)
		self.command_definition["Local-Set-Width"] 				= lambda x: self.psh_Local_Set_Width(x[len("Local-Set-Width"):].strip())
		self.command_definition["Local-Upload"] 				= lambda x: self.psh_Local_Upload(x[len("Local-Upload"):].strip())
		self.command_definition["Local-Download"] 				= lambda x: self.psh_Local_Download(x[len("Local-Download"):].strip())
		self.command_definition["Local-Download-Commands"] 		= lambda x: self.psh_Local_Download_Commands()		
		self.command_definition["Local-Enumerate-System"] 		= lambda x: self.psh_Local_Enumerate_System()
		self.command_definition["Local-Check-Status"] 			= lambda x: self.psh_Local_Check_Status()
		self.command_definition["Local-Spawn-Meterpreter"]		= lambda x: self.psh_Local_Spawn_Shell(conf_name.METERPRETER)
		self.command_definition["Local-Spawn-Reverse-Shell"]	= lambda x: self.psh_Local_Spawn_Shell(conf_name.REVERSE_SHELL)
		self.command_definition["Local-Credential-Create"] 		= lambda x: self.psh_Local_Credential(True)
		self.command_definition["Local-Credential-List"] 		= lambda x: self.psh_Local_Credential()
		self.command_definition["clear"]						= lambda x: self.psh_Local_Clear()
				
		# Define autocomplete
		readline.parse_and_bind("tab: complete")
		readline.set_completer(self.cmd_complete)
		readline.set_completion_display_matches_hook(self.cmd_match_display_hook)
		readline.set_completer_delims("") 
Example #27
Source File: console.py    From rpl-attacks with GNU Affero General Public License v3.0 5 votes vote down vote up
def cmdloop(self, intro=None):
        try:
            import readline
            readline.set_completer_delims(' ')
            super(Console, self).cmdloop()
        except (KeyboardInterrupt, EOFError):
            print('')
            self.cmdloop() 
Example #28
Source File: shell.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self) -> 'Completer':
        with suppress(Exception):
            readline.read_history_file(self.history_path)
        readline.set_completer(self.complete)
        delims = readline.get_completer_delims()
        readline.set_completer_delims(delims.replace('-', ''))
        return self 
Example #29
Source File: main.py    From rshell with MIT License 5 votes vote down vote up
def __init__(self, filename=None, timing=False, **kwargs):
        cmd.Cmd.__init__(self, **kwargs)
        if 'stdin' in kwargs:
            cmd.Cmd.use_rawinput = 0

        self.real_stdout = self.stdout
        self.smart_stdout = SmartFile(self.stdout)

        self.stderr = SmartFile(sys.stderr)

        self.filename = filename
        self.line_num = 0
        self.timing = timing

        global cur_dir
        cur_dir = os.getcwd()
        self.prev_dir = cur_dir
        self.columns = shutil.get_terminal_size().columns

        self.redirect_dev = None
        self.redirect_filename = ''
        self.redirect_mode = ''

        self.quit_when_no_output = False
        self.quit_serial_reader = False
        readline.set_completer_delims(DELIMS)

        self.set_prompt() 
Example #30
Source File: readline.py    From daudin with MIT License 5 votes vote down vote up
def setupReadline(local):
    """Initialize the readline library and command history.

    @return: A C{bool} to indicate whether standard input is a terminal
        (and therefore interactive).
    """
    readline.parse_and_bind('tab: complete')
    readline.set_completer_delims(' \t\n')
    readline.set_completer(Completer(local).complete)

    # Readline code from https://docs.python.org/3.7/library/readline.html
    histfile = os.path.join(os.path.expanduser('~'), '.daudin_history')

    try:
        readline.read_history_file(histfile)
        historyLen = readline.get_current_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        historyLen = 0

    try:
        readline.append_history_file
    except AttributeError:
        # We won't be able to save readline history. This can happen on
        # Python 3.5 at least - not sure why.
        pass
    else:
        import atexit

        def saveHistory(prevHistoryLen, histfile):
            newHistoryLen = readline.get_current_history_length()
            readline.set_history_length(1000)
            readline.append_history_file(newHistoryLen - prevHistoryLen,
                                         histfile)

        atexit.register(saveHistory, historyLen, histfile)

    return True