我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用readline.set_completer()。
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)
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)
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")
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
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
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
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)
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()
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")
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))
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)
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)
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
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()
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
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.'
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.'
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 :-(')
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)
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
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)
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)
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
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
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')
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)
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)
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)
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')
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
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)
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')
def __exit__(self, unused_type, unused_value, unused_traceback): readline.set_completer_delims(self._original_delims) readline.set_completer(self._original_completer)