Python readline.set_completer() Examples

The following are 30 code examples of readline.set_completer(). 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: pundle.py    From pundler with BSD 2-Clause "Simplified" License 9 votes vote down vote up
def run_console(glob):
    import readline
    import rlcompleter
    import atexit
    import code

    history_path = os.path.expanduser("~/.python_history")

    def save_history(history_path=history_path):
        readline.write_history_file(history_path)
    if os.path.exists(history_path):
        readline.read_history_file(history_path)

    atexit.register(save_history)

    readline.set_completer(rlcompleter.Completer(glob).complete)
    readline.parse_and_bind("tab: complete")
    code.InteractiveConsole(locals=glob).interact() 
Example #2
Source File: autocomplete.py    From vault with MIT License 7 votes vote down vote up
def get_input_autocomplete(message=''):
    """ Allow user to type input and provide auto-completion """

    # Apple does not ship GNU readline with OS X.
    # It does ship BSD libedit which includes a readline compatibility interface.
    # Source: https://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion
    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
    readline.set_completer(autocomplete)

    try:
        return input(message).strip()
    except KeyboardInterrupt:
        return False
    except Exception:  # Other Exception
        return False 
Example #3
Source File: defs.py    From hadrian with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        """Create the main mode.

        If titus.inspector.defs.CONFIG_DIRECTORY_EXISTS is ``True``, get the readline history file from the user's titus.inspector.defs.CONFIG_DIRECTORY.
        """

        if CONFIG_DIRECTORY_EXISTS:
            self.historyPath = os.path.join(os.path.expanduser(CONFIG_DIRECTORY), self.historyFileName)
            if not os.path.exists(self.historyPath):
                open(self.historyPath, "w").close()

            self.active = True
            self.tabCompleter = TabCompleter(self)
            readline.read_history_file(self.historyPath)
            readline.set_completer(self.tabCompleter.complete)

            def writehistory():
                if self.active:
                    readline.write_history_file(self.historyPath)
            atexit.register(writehistory) 
Example #4
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 #5
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 #6
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 #7
Source File: PupyCmd.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def do_python(self,arg):
		""" start the local python interpreter (for debugging purposes) """
		orig_exit=builtins.exit
		orig_quit=builtins.quit
		def disabled_exit(*args, **kwargs):
			self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
		builtins.exit=disabled_exit
		builtins.quit=disabled_exit
		oldcompleter=readline.get_completer()
		try:
			local_ns={"pupsrv":self.pupsrv}
			readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
			readline.parse_and_bind('tab: complete')
			code.interact(local=local_ns)
		except Exception as e:
			self.display_error(str(e))
		finally:
			readline.set_completer(oldcompleter)
			readline.parse_and_bind('tab: complete')
			builtins.exit=orig_exit
			builtins.quit=orig_quit 
Example #8
Source File: PupyCmd.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def do_python(self,arg):
		""" start the local python interpreter (for debugging purposes) """
		orig_exit=builtins.exit
		orig_quit=builtins.quit
		def disabled_exit(*args, **kwargs):
			self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
		builtins.exit=disabled_exit
		builtins.quit=disabled_exit
		oldcompleter=readline.get_completer()
		try:
			local_ns={"pupsrv":self.pupsrv}
			readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
			readline.parse_and_bind('tab: complete')
			code.interact(local=local_ns)
		except Exception as e:
			self.display_error(str(e))
		finally:
			readline.set_completer(oldcompleter)
			readline.parse_and_bind('tab: complete')
			builtins.exit=orig_exit
			builtins.quit=orig_quit 
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: rlcompleter.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, namespace = None):
        """Create a new completer for the command line.

        Completer([namespace]) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)
        """

        if namespace and not isinstance(namespace, dict):
            raise TypeError('namespace must be a dictionary')

        # Don't bind to namespace quite yet, but flag whether the user wants a
        # specific namespace or to use __main__.__dict__. This will allow us
        # to bind to __main__.__dict__ at completion time, not now.
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace 
Example #15
Source File: rlcompleter.py    From scylla with Apache License 2.0 5 votes vote down vote up
def __init__(self, namespace = None):
        """Create a new completer for the command line.

        Completer([namespace]) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)
        """

        if namespace and not isinstance(namespace, dict):
            raise TypeError('namespace must be a dictionary')

        # Don't bind to namespace quite yet, but flag whether the user wants a
        # specific namespace or to use __main__.__dict__. This will allow us
        # to bind to __main__.__dict__ at completion time, not now.
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace 
Example #16
Source File: main.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self) -> 'HistoryCompleter':
        if self.history_path:
            with suppress(Exception):
                readline.read_history_file(self.history_path)
            readline.set_completer(self.complete)
        return self 
Example #17
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 #18
Source File: rlcompleter.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, namespace = None):
        """Create a new completer for the command line.

        Completer([namespace]) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)
        """

        if namespace and not isinstance(namespace, dict):
            raise TypeError('namespace must be a dictionary')

        # Don't bind to namespace quite yet, but flag whether the user wants a
        # specific namespace or to use __main__.__dict__. This will allow us
        # to bind to __main__.__dict__ at completion time, not now.
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace 
Example #19
Source File: complete.py    From weeman with GNU General Public License v3.0 5 votes vote down vote up
def complete(array):
	completer = auto(array)
	readline.set_completer(completer.complete)
	readline.parse_and_bind('tab:complete') 
Example #20
Source File: dexnet_cli.py    From PointNetGPD with MIT License 5 votes vote down vote up
def __init__(self):
        # init core members
        self.dexnet_api = dexnet.DexNet()

        # setup command line parsing
        self.comp = Completer()
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.comp.complete)

        # display welcome message
        self.display_welcome() 
Example #21
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 #22
Source File: SniffAir.py    From SniffAir with MIT License 5 votes vote down vote up
def choice():
		global name
		global module
		try:
			if module == "":
				readline.set_completer(completer)
				readline.set_completer_delims('')
				if 'libedit' in readline.__doc__:
					readline.parse_and_bind("bind ^I rl_complete")
				else:
					readline.parse_and_bind("tab: complete")
				raw_choice = raw_input(" >>  [" + name + "]# ")
				choice = raw_choice
				exec_menu(choice)
			else:
				readline.set_completer(completer)
				readline.set_completer_delims('')
				if 'libedit' in readline.__doc__:
					readline.parse_and_bind("bind ^I rl_complete")
				else:
					readline.parse_and_bind("tab: complete")
				raw_choice = raw_input(" >>  [" + name + "][" + module + "]# ")
				choice = raw_choice
				exec_menu(choice)
		except EOFError:
			pass
		except KeyboardInterrupt:
			exec_menu('exit') 
Example #23
Source File: completer.py    From pythem with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, console):
        tab = readline.parse_and_bind("tab: complete")
        if console == "pythem":
            historyPath = ".pythem_history".format(path)
            readline.read_history_file(historyPath)
            completer = readline.set_completer(self.pythem)
            # readline.write_history_file(historyPath)

        if console == "xploit":
            completer = readline.set_completer(self.xploit) 
Example #24
Source File: cli.py    From pytgbot with GNU General Public License v3.0 5 votes vote down vote up
def register_tab_completion(self):
        # Register our completer function
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)
        # Use the tab key for completion
    # end def 
Example #25
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.
        """

        # An almost perfect copy from Cmd; however, the pseudo_raw_input portion
        # has been split out so that it can be called separately

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey+": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    line = self.pseudo_raw_input(self.prompt)
                if (self.echo) and (isinstance(self.stdin, file)):
                    self.stdout.write(line + '\n')
                stop = self.onecmd_plus_hooks(line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
            return stop 
Example #26
Source File: __main__.py    From signac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _main_import_interactive(project, origin, args):
    from .contrib.import_export import _prepare_import_into_project
    if args.move:
        raise ValueError("Cannot use '--move' in combination with '--sync-interactive'.")

    with project.temporary_project() as tmp_project:
        _print_err("Prepare data space for import...")
        with _prepare_import_into_project(origin, tmp_project, args.schema_path) as data_mapping:
            paths = dict()
            for src, copy_executor in tqdm(
                    dict(data_mapping).items(), desc='Import to temporary project'):
                paths[src] = copy_executor()

            local_ns = dict(
                signac=importlib.import_module(__package__),
                project=project, pr=project,
                tmp_project=tmp_project)
            if READLINE:
                readline.set_completer(Completer(local_ns).complete)
                readline.parse_and_bind('tab: complete')
            code.interact(
                local=local_ns,
                banner=SHELL_BANNER_INTERACTIVE_IMPORT.format(
                    python_version=sys.version,
                    signac_version=__version__,
                    project_id=project.get_id(),
                    job_banner='',
                    root_path=project.root_directory(),
                    workspace_path=project.workspace(),
                    size=len(project),
                    origin=args.origin))

            return paths 
Example #27
Source File: interact.py    From neleval with Apache License 2.0 5 votes vote down vote up
def run_python(local):
    import code
    try:
        import readline
    except ImportError:
        pass
    else:
        import rlcompleter
        readline.set_completer(rlcompleter.Completer(local).complete)
        readline.parse_and_bind('tab:complete')
    code.interact(local=local) 
Example #28
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __exit__(self, etype, exc, tb):
        self.rl.set_completer(self.old_completer)
        if self.histfile:
            self.rl.write_history_file(self.histfile) 
Example #29
Source File: repl.py    From sdb with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 target: drgn.Program,
                 vocabulary: List[str],
                 prompt: str = "sdb> ",
                 closing: str = ""):
        self.prompt = prompt
        self.closing = closing
        self.vocabulary = vocabulary
        self.target = target
        self.histfile = ""
        readline.set_completer(REPL.__make_completer(vocabulary))
        readline.parse_and_bind("tab: complete") 
Example #30
Source File: plac_ext.py    From plac with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, completions, case_sensitive=True, histfile=None):
        self.completions = completions
        self.case_sensitive = case_sensitive
        self.histfile = histfile
        if not case_sensitive:
            self.completions = [c.upper() for c in completions]
        import readline
        self.rl = readline
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)