Python readline 模块,set_completer() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用readline.set_completer()

项目:rudra    作者:7h3rAm    | 项目源码 | 文件源码
def interactive(self):
    utils.set_prompt(ps1="(rudra) ", ps2="... ")

    import os
    import readline
    import rlcompleter
    import atexit

    histfile = os.path.join(os.environ["HOME"], ".rudrahistory")
    if os.path.isfile(histfile):
      readline.read_history_file(histfile)
    atexit.register(readline.write_history_file, histfile)

    r = self
    print "Use the \"r\" object to analyze files"

    vars = globals()
    vars.update(locals())
    readline.set_completer(rlcompleter.Completer(vars).complete)
    readline.parse_and_bind("tab: complete")

    del os, histfile, readline, rlcompleter, atexit
    code.interact(banner="", local=vars)
项目:Acedia    作者:Lvl4Sword    | 项目源码 | 文件源码
def log_exercise(settings, logs, start_log):
    completer = MyCompleter([str(k) for k in workouts])
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')

    while True:
        # because windows has to be special
        if sys.platform.startswith('win'):
            choose_extra = "(Tab for options)"
        else:
            choose_extra = "(Double tab for options)"
        choose_ = input('What workout did you do? {0}: '.format(choose_extra))
        if choose_.capitalize() not in workouts.keys():
            pass
        else:
            if choose_.capitalize() == 'Cardio':
                cardio.main(settings, logs)
            elif choose_.capitalize() == 'Log':
                print("Not yet done")
            elif choose_.capitalize() == 'Settings':
                settings_change(settings)
            else:
                physical.main(choose_, settings)
            body_checks(settings, start_log)
项目:routersploit    作者:reverse-shell    | 项目源码 | 文件源码
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")
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
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")
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def run(self, args):
        try:
            if not self.client.conn.modules["os.path"].exists("C:\\WIndows\\system32\\Packet.dll"):
                raise PupyModuleError("WinPcap is not installed !. You should download/upload NPcap (https://github.com/nmap/npcap/releases) and install it silently (with the /S flag) ")
            if not self.client.conn.modules['ctypes'].windll.Shell32.IsUserAnAdmin():
                self.warning("you are running this module without beeing admin")
            with redirected_stdo(self.client.conn):
                old_completer=readline.get_completer()
                try:
                    psc=self.client.conn.modules['pyshell.controller'].PyShellController()
                    readline.set_completer(psc.get_completer())
                    readline.parse_and_bind('tab: complete')
                    psc.write("from scapy.all import *")
                    while True:
                        cmd=raw_input(">>> ")
                        psc.write(cmd)
                finally:
                    readline.set_completer(old_completer)
                    readline.parse_and_bind('tab: complete')
        except KeyboardInterrupt:
            pass
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def run(self, args):
        try:
            with redirected_stdo(self.client.conn):
                old_completer=readline.get_completer()
                try:
                    psc=self.client.conn.modules['pyshell.controller'].PyShellController()
                    readline.set_completer(psc.get_completer())
                    readline.parse_and_bind('tab: complete')
                    while True:
                        cmd=raw_input(">>> ")
                        psc.write(cmd)
                finally:
                    readline.set_completer(old_completer)
                    readline.parse_and_bind('tab: complete')
        except KeyboardInterrupt:
            pass
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir, env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        history_file = os.path.join(adir, '.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def run(self, args):
        try:
            if not self.client.conn.modules["os.path"].exists("C:\\WIndows\\system32\\Packet.dll"):
                raise PupyModuleError("WinPcap is not installed !. You should download/upload NPcap (https://github.com/nmap/npcap/releases) and install it silently (with the /S flag) ")
            if not self.client.conn.modules['ctypes'].windll.Shell32.IsUserAnAdmin():
                self.warning("you are running this module without beeing admin")
            with redirected_stdo(self.client.conn):
                old_completer=readline.get_completer()
                try:
                    psc=self.client.conn.modules['pyshell.controller'].PyShellController()
                    readline.set_completer(psc.get_completer())
                    readline.parse_and_bind('tab: complete')
                    psc.write("from scapy.all import *")
                    while True:
                        cmd=raw_input(">>> ")
                        psc.write(cmd)
                finally:
                    readline.set_completer(old_completer)
                    readline.parse_and_bind('tab: complete')
        except KeyboardInterrupt:
            pass
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def run(self, args):
        try:
            with redirected_stdo(self.client.conn):
                old_completer=readline.get_completer()
                try:
                    psc=self.client.conn.modules['pyshell.controller'].PyShellController()
                    readline.set_completer(psc.get_completer())
                    readline.parse_and_bind('tab: complete')
                    while True:
                        cmd=raw_input(">>> ")
                        psc.write(cmd)
                finally:
                    readline.set_completer(old_completer)
                    readline.parse_and_bind('tab: complete')
        except KeyboardInterrupt:
            pass
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
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
项目:proxmoxsh    作者:timur-enikeev    | 项目源码 | 文件源码
def __init__(self):
        try:
            self.read_config()
        except:
            c = {}
            c['url'] = raw_input(u"Enter server hostname or IP address: ")
            c['username'] = raw_input(u"Enter user name: ")
            c['password'] = getpass(u"Enter password: ")
            self.config['credentials'] = c
        self.pve = Pveconn(**self.config['credentials'])
        if '-c' in sys.argv:
            command = sys.argv[sys.argv.index('-c')+1:]
            self.parse_command(command)
        else:
            readline.parse_and_bind("tab: complete")
            readline.set_completer(self.complete)
            self.wait()
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir, env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        history_file = os.path.join(adir, '.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:jiveplot    作者:haavee    | 项目源码 | 文件源码
def __exit__(self, ex_tp, ex_val, ex_tb):
        if not haveReadline:
            return False
        try:
            # update the history for this project
            readline.write_history_file(self.historyFile)
        except Exception as E:
            print "Failed to write history to {0} - {1}".format(self.historyFile, E)
        # put back the original history!
        readline.clear_history()
        readline.read_history_file(self.oldhistFile)
        os.unlink(self.oldhistFile)

        # and put back the old completer
        readline.set_completer(self.oldCompleter)

# linegenerators, pass one of these to the "run"
# method of the CommandLineInterface object
#import ctypes
#rllib = ctypes.cdll.LoadLibrary("libreadline.so")
#rl_line_buffer = ctypes.c_char_p.in_dll(rllib, "rl_line_buffer")
#rl_done        = ctypes.c_int.in_dll(rllib, "rl_done")
项目:pyshell    作者:oglops    | 项目源码 | 文件源码
def setup(histfn=None, button='tab',verbose=1):
    if histfn is None: 
        base = os.getenv('HOME')
        if not base: 
            import tempfile
            base = tempfile.gettempdir()
        histfn = os.path.join(base, '.pythonhist')
    import readline 
    completer = Completer()
    readline.set_completer_delims('')
    readline.set_completer(completer.rl_complete)
    readline.parse_and_bind(button+': complete')
    if histfn:
        setup_readline_history(histfn)
    if verbose:
        print ("Welcome to rlcompleter2 %s" % __version__)
        print ("for nice experiences hit <%s> multiple times"%(button))
项目:featherduster    作者:nccgroup    | 项目源码 | 文件源码
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)
项目:featherduster    作者:nccgroup    | 项目源码 | 文件源码
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)
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir, env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        history_file = os.path.join(adir, '.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:tensorforce-benchmark    作者:reinforceio    | 项目源码 | 文件源码
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
项目:koadic    作者:zerosum0x0    | 项目源码 | 文件源码
def get_command(self, prompt, auto_complete_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)
        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()
项目:isf    作者:w3h    | 项目源码 | 文件源码
def pre_input(self, completefn):
        if self.raw_input:
            if HAVE_READLINE:
                import atexit
                self.old_completer = readline.get_completer()
                # Fix Bug #3129: Limit the history size to consume less memory
                readline.set_history_length(self.historysize)
                readline.set_completer(completefn)
                readline.parse_and_bind(self.completekey+": complete")
                try:
                    readline.read_history_file()
                except IOError:
                    pass
                atexit.register(readline.write_history_file)
                self.havecolor = True
                if mswindows and self.enablecolor:
                    self.cwrite = readline.GetOutputFile().write_color
                else:
                    self.cwrite = self.stdout.write
项目:rekall-agent-server    作者:rekall-innovations    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir, env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        history_file = os.path.join(adir, '.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:pyflume    作者:jiangruocheng    | 项目源码 | 文件源码
def config():
    show()
    choose = raw_input('???????ip????????all:')
    try:
        if 'all' == choose:
            ip_list = SLAVE_LIST
        else:
            ip_list = [SLAVE_LIST[int(i)] for i in choose.split()]
        readline.set_completer(path_completer)
        _path = raw_input('??????????:')
        for ip in ip_list:
            print 'IP: ', ip, 'is proccessing...'
            address = "http://{}:12001/".format(ip)
            proxy = xmlrpclib.ServerProxy(address)
            with open(_path, 'r') as f:
                print 'Result:', str(proxy.config(f.read()))
            proxy('close')
    except:
        print traceback.format_exc()
    print 'Done.'
项目:pyflume    作者:jiangruocheng    | 项目源码 | 文件源码
def upload_script():
    show()
    choose = raw_input('???????ip????????all:')
    try:
        if 'all' == choose:
            ip_list = SLAVE_LIST
        else:
            ip_list = [SLAVE_LIST[int(i)] for i in choose.split()]
        readline.set_completer(path_completer)
        _path = raw_input('??????????:')
        for ip in ip_list:
            print 'IP: ', ip, 'is proccessing...'
            address = "http://{}:12001/".format(ip)
            proxy = xmlrpclib.ServerProxy(address)
            with open(_path, 'r') as f:
                print 'Result:', str(proxy.upload_script(os.path.basename(_path), f.read()))
            proxy('close')
    except:
        print traceback.format_exc()

    print 'Done.'
项目:slugiot-client    作者:slugiot    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir, env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        history_file = os.path.join(adir, '.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
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 is not available :-(')
项目:isf    作者:dark-lbp    | 项目源码 | 文件源码
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")
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
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 is not available :-(')
项目:routersploit    作者:Exploit-install    | 项目源码 | 文件源码
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")
项目:shadowbroker-auto    作者:wrfly    | 项目源码 | 文件源码
def pre_input(self, completefn):
        if self.raw_input:
            if HAVE_READLINE:
                import atexit
                self.old_completer = readline.get_completer()
                # Fix Bug #3129: Limit the history size to consume less memory
                readline.set_history_length(self.historysize)   
                readline.set_completer(completefn)
                readline.parse_and_bind(self.completekey+": complete")
                try:
                    readline.read_history_file()
                except IOError:
                    pass
                atexit.register(readline.write_history_file)
                self.havecolor = True
                if mswindows and self.enablecolor:
                    self.cwrite = readline.GetOutputFile().write_color
                else:
                    self.cwrite = self.stdout.write
项目:zielen    作者:lostatc    | 项目源码 | 文件源码
def set_path_autocomplete() -> None:
    """Enable file path autocompletion for GNU readline."""
    def autocomplete(text: str, state: int) -> str:
        expanded_path = os.path.expanduser(text)

        if os.path.isdir(expanded_path):
            possible_paths = glob.glob(os.path.join(expanded_path, "*"))
        else:
            possible_paths = glob.glob(expanded_path + "*")

        if expanded_path != text:
            possible_paths = [contract_user(path) for path in possible_paths]
        possible_paths.append(None)

        return possible_paths[state]

    readline.parse_and_bind("tab: complete")
    readline.set_completer_delims("")
    readline.set_completer(autocomplete)
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
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 is not available :-(')
项目:isambard    作者:woolfson-group    | 项目源码 | 文件源码
def main(args):
    # setup the line parser for user input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)

    settings_path = home_dir / settings_file_name
    if args.circleci:
        install_for_circleci(settings_path)
        return
    if settings_path.exists() and (not args.overwrite):
        raise FileExistsError(
            '{FAIL}Configuration files found, these can be overwritten using the "-o" flag.{END_C}'.format(
                **text_colours))
    install(settings_path, basic=args.basic)
    print('{BOLD}{HEADER}Configuration completed successfully.{END_C}'.format(**text_colours))
    return
项目:StuffShare    作者:StuffShare    | 项目源码 | 文件源码
def enable_autocomplete_and_history(adir,env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("bind ^I rl_complete"
                                if sys.platform == 'darwin'
                                else "tab: complete")
        history_file = os.path.join(adir,'.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete)
项目:iOSSecAudit    作者:alibaba    | 项目源码 | 文件源码
def init_history(self, histfile):

        #readline.parse_and_bind("bind ^I rl_complete")

        # Register our completer function
        readline.set_completer(SimpleCompleter(G.cmmands.keys()).complete)


        #readline.set_completer(TabCompleter().complete)
        ### Add autocompletion
        if 'libedit' in readline.__doc__:
            readline.parse_and_bind("bind -e")
            readline.parse_and_bind("bind '\t' rl_complete")
        else:
            readline.parse_and_bind("tab: complete")

        # Use the tab key for completion
        #readline.parse_and_bind('tab: complete')
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except:
                pass

            atexit.register(self.save_history, histfile)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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
项目:RSPET    作者:panagiks    | 项目源码 | 文件源码
def readline_completer(words):
    readline.set_completer(autocomplete(words).complete)
    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set completion-ignore-case on')
项目:octopus    作者:octopus-platform    | 项目源码 | 文件源码
def _init_readline(self):
        readline.parse_and_bind("tab: complete")
        try:
            init_file = self.init_file()
            if init_file:
                readline.read_init_file(os.path.expanduser(self.init_file()))
        except FileNotFoundError:
            pass
        readline.set_completer(OctopusShellCompleter(self.octopus_shell).complete)
项目:octopus    作者:octopus-platform    | 项目源码 | 文件源码
def _init_readline(self):
        readline.parse_and_bind("tab: complete")
        try:
            init_file = self.init_file()
            if init_file:
                readline.read_init_file(os.path.expanduser(self.init_file()))
        except FileNotFoundError:
            pass
        readline.set_completer(OctopusShellCompleter(self.octopus_shell).complete)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def handle(self, **options):
        try:
            if options['plain']:
                # Don't bother loading IPython, because the user wants plain Python.
                raise ImportError

            self.run_shell(shell=options['interface'])
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            imported_objects = {}
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
            if not options['no_startup']:
                for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'):
                    if not pythonrc:
                        continue
                    pythonrc = os.path.expanduser(pythonrc)
                    if not os.path.isfile(pythonrc):
                        continue
                    try:
                        with open(pythonrc) as handle:
                            exec(compile(handle.read(), pythonrc, 'exec'), imported_objects)
                    except NameError:
                        pass
            code.interact(local=imported_objects)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def python(self, options):
        import code
        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        imported_objects = {}
        try:  # Try activating rlcompleter, because it's handy.
            import readline
        except ImportError:
            pass
        else:
            # We don't have to wrap the following import in a 'try', because
            # we already know 'readline' was imported successfully.
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(imported_objects).complete)
            # Enable tab completion on systems using libedit (e.g. Mac OSX).
            # These lines are copied from Lib/site.py on Python 3.4.
            readline_doc = getattr(readline, '__doc__', '')
            if readline_doc is not None and 'libedit' in readline_doc:
                readline.parse_and_bind("bind ^I rl_complete")
            else:
                readline.parse_and_bind("tab:complete")

        # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
        # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
        if not options['no_startup']:
            for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'):
                if not pythonrc:
                    continue
                pythonrc = os.path.expanduser(pythonrc)
                if not os.path.isfile(pythonrc):
                    continue
                try:
                    with open(pythonrc) as handle:
                        exec(compile(handle.read(), pythonrc, 'exec'), imported_objects)
                except NameError:
                    pass
        code.interact(local=imported_objects)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def start( control=1):
    if control == 1:
        from .db import ret2
        readline.set_completer(SimpleCompleter(ret2()).complete)
        readline.parse_and_bind('tab: complete')
    else:
        from .db import ret
        readline.set_completer(SimpleCompleter(ret()).complete)
        readline.parse_and_bind('tab: complete')
项目:whatsapp-rest-webservice    作者:svub    | 项目源码 | 文件源码
def __init__(self):
        self.sentCache = {}
        self.commands = {}
        self.acceptingInput = False
        self.lastPrompt = True
        self.blockingQueue = Queue.Queue()

        self._queuedCmds = []

        readline.set_completer(self.complete)
        readline.parse_and_bind('tab: complete')

        members = inspect.getmembers(self, predicate = inspect.ismethod)
        for m in members:
            if hasattr(m[1], "clidesc"):
                fname = m[0]
                fn = m[1]
                try:
                    cmd, subcommand = fname.split('_')
                except ValueError:
                    cmd = fname
                    subcommand = "_"


                if not cmd in self.commands:
                    self.commands[cmd] = {}

                self.commands[cmd][subcommand] = {
                   "args": inspect.getargspec(fn)[0][1:],
                   "optional": len(inspect.getargspec(fn)[3]) if inspect.getargspec(fn)[3] else 0,
                   "desc": fn.clidesc,
                   "fn": fn,
                   "order": fn.cliorder
                }
        #self.cv = threading.Condition()
        self.inputThread = threading.Thread(target = self.startInputThread)
        self.inputThread.daemon = True
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def python(self, options):
        import code
        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        imported_objects = {}
        try:  # Try activating rlcompleter, because it's handy.
            import readline
        except ImportError:
            pass
        else:
            # We don't have to wrap the following import in a 'try', because
            # we already know 'readline' was imported successfully.
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(imported_objects).complete)
            # Enable tab completion on systems using libedit (e.g. macOS).
            # These lines are copied from Lib/site.py on Python 3.4.
            readline_doc = getattr(readline, '__doc__', '')
            if readline_doc is not None and 'libedit' in readline_doc:
                readline.parse_and_bind("bind ^I rl_complete")
            else:
                readline.parse_and_bind("tab:complete")

        # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
        # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
        if not options['no_startup']:
            for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]):
                if not pythonrc:
                    continue
                if not os.path.isfile(pythonrc):
                    continue
                try:
                    with open(pythonrc) as handle:
                        exec(compile(handle.read(), pythonrc, 'exec'), imported_objects)
                except NameError:
                    pass
        code.interact(local=imported_objects)
项目:shellsploit-framework    作者:Exploit-install    | 项目源码 | 文件源码
def start( control=1):
    if control == 1:
        from .db import ret2
        readline.set_completer(SimpleCompleter(ret2()).complete)
        readline.parse_and_bind('tab: complete')
    else:
        from .db import ret
        readline.set_completer(SimpleCompleter(ret()).complete)
        readline.parse_and_bind('tab: complete')
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __enter__(self):
        self._original_completer = readline.get_completer()
        self._original_delims = readline.get_completer_delims()

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')

        # readline can be implemented using GNU readline or libedit
        # which have different configuration syntax
        if 'libedit' in readline.__doc__:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __exit__(self, unused_type, unused_value, unused_traceback):
        readline.set_completer_delims(self._original_delims)
        readline.set_completer(self._original_completer)