本文整理汇总了Python中readline.get_completer函数的典型用法代码示例。如果您正苦于以下问题:Python get_completer函数的具体用法?Python get_completer怎么用?Python get_completer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_completer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getinput
def getinput(question, default="", reader=raw_input, completer=None, width=_defaultwidth): # pragma: no cover
"""
http://stackoverflow.com/questions/2617057/\
supply-inputs-to-python-unittests
"""
if reader == raw_input:
if not _readline_available:
val = raw_input(question.ljust(width))
if val:
return val
else:
return default
else:
def defaulter():
"""define default behavior startup"""
readline.insert_text(default)
if _readline_available:
readline.set_startup_hook(defaulter)
readline.get_completer()
readline.set_completer(completer)
x = raw_input(question.ljust(width))
if _readline_available:
readline.set_startup_hook()
return x if x else default
else:
return reader()
示例2: defaulter
def defaulter():
"""define default behavior startup"""
if _readline_available:
readline.insert_text(default)
readline.set_startup_hook(defaulter)
readline.get_completer()
readline.set_completer(completer)
示例3: test_context_manager_with_unmocked_readline
def test_context_manager_with_unmocked_readline(self):
from letsencrypt.display import completer
reload_module(completer)
original_completer = readline.get_completer()
original_delims = readline.get_completer_delims()
with completer.Completer():
pass
self.assertEqual(readline.get_completer(), original_completer)
self.assertEqual(readline.get_completer_delims(), original_delims)
示例4: execute_interactive
def execute_interactive():
""" Runs the command mode once, reading the standard input for a command
and executing it. Will return execution once a command has been executed
or if an invalid command was passed.
"""
old_completer = readline.get_completer()
readline.set_completer(__readline_completer)
readline.parse_and_bind('tab: complete')
term.enter_buffer()
# default raw mode is not readline friendly.
# restore after saving display, for restoring is destructive
term.restore_tty()
try:
cmd_name = raw_input('REACH:')
except:
# return to raw_mode
term.set_raw()
readline.set_completer(old_completer)
term.leave_buffer()
return
cmd_args = [x for x in cmd_name.split(' ') if x != '']
if cmd_args and cmd_args[0] in registry:
try:
registry[cmd_args[0]][1](cmd_args)
except Exception, e:
print(e)
term.pause()
示例5: run
def run(self):
# Preserve existing history
if self.preserve_history:
old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
old_history = filter(lambda x: x is not None, old_history)
readline.clear_history()
map(readline.add_history, self.history)
old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind("bind ^I rl_complete")
while True:
cmdline = raw_input("%s > " % (self.prefix,))
self.last_wd_complete = ("", ())
if not cmdline:
continue
# Try to dispatch command
try:
self.execute(cmdline)
except SystemExit, e:
print "Exiting shell: %s" % (e.code,)
break
except UnknownCommand, e:
print "Command '%s' unknown." % (e,)
示例6: run
def run(self, line):
def _formatOutput(res):
if isinstance(res, str):
return res
else:
try:
return "\n".join(_formatOutput(r) for r in res)
except TypeError:
return str(res)
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
filePath = raw_input("Please specify a path to the output file: ").strip()
readline.set_completer(ishellCompleter)
if os.path.isfile(filePath):
confirm = raw_input("File already exists and will be overwritten, confirm? [y/N] ")
if confirm is "" or confirm[0] not in ("y", "Y"):
print "Canceled."
return
with open(filePath, "w+") as handle:
handle.write(_formatOutput(feathermodules.results))
示例7: interact
def interact(self, cmd=None):
_reset_readline()
if cmd and isinstance(cmd, BaseCommands):
self.push_command(cmd)
if readline:
oc = readline.get_completer()
readline.set_completer(self._rl_completer)
try:
try:
while 1:
ui = self._cmd._ui
try:
line = ui.user_input()
if not line:
continue
while self.feed(line+"\n"):
line = ui.more_user_input()
except EOFError:
self._cmd._print()
self.pop_command()
except (CommandQuit, CommandExit): # last command does this
pass
finally:
if readline:
readline.set_completer(oc)
if self._historyfile:
try:
readline.write_history_file(self._historyfile)
except:
pass
示例8: run_interactive
def run_interactive(self):
'''
Starts interactive CLI mode.
'''
history = self.prefs['path_history']
index = self.prefs['path_history_index']
if history and index:
if index < len(history):
try:
target = self._root_node.get_node(history[index])
except ValueError:
self._current_node = self._root_node
else:
self._current_node = target
try:
old_completer = readline.get_completer()
self._cli_loop()
except KeyboardInterrupt:
self.con.raw_write('\n')
self.run_interactive()
except Exception:
self.log.exception()
self.run_interactive()
finally:
readline.set_completer(old_completer)
示例9: cmdloop
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.
"""
self.preloop()
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
if 'libedit' in readline.__doc__:
# readline linked to BSD libedit
if self.completekey == 'tab':
key = '^I'
else:
key = self.completekey
readline.parse_and_bind('bind %s rl_complete' % (key,))
else:
# readline linked to the real readline
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:
if self.use_rawinput:
try:
line = input(self.prompt)
except EOFError:
line = 'EOF'
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line.rstrip('\r\n')
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
try:
import readline
readline.set_completer(self.old_completer)
except ImportError:
pass
示例10: loop
def loop(self):
previous_completer = readline.get_completer()
readline.parse_and_bind("tab: complete")
readline.set_completer(self.walk)
prompt = self.prompt + self.prompt_delim
if not ishell._current_prompt:
previous_prompt = prompt
else:
previous_prompt = ishell._current_prompt
ishell._current_prompt = prompt
while 1:
try:
sys.stdout.write("\r")
if self._exit:
break
input_ = raw_input(prompt + " ")
if not input_:
self.help()
elif input_ in ('quit', 'exit'):
break
else:
self.walk_and_run(input_)
except Exception, e:
print "Error: %s" % e
sys.exit(1)
示例11: cmdloop
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.
"""
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("%s\n" % self.intro)
self._stopping = False
success = True
while not self._stopping:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
if self.use_rawinput:
try:
line = py3bro.input(self.prompt)
except EOFError:
line = "EOF"
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not line:
line = "EOF"
else:
line = line.rstrip("\r\n")
line = self.precmd(line)
try:
success = self.onecmd(line)
except (CommandSyntaxError, InvalidNodeError, LockError) as err:
# Note that here we do not attempt to catch all BroControl
# exceptions; letting some just terminate the program to
# avoid getting in an unknown state (e.g. error while
# reloading the config).
success = False
print("Error: %s" % err)
self.postcmd(False, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
try:
import readline
readline.set_completer(self.old_completer)
except ImportError:
pass
return success
示例12: wrapper
def wrapper(*args, **kwargs):
try:
import readline
handle_readline = True
except ImportError:
handle_readline = False
if handle_readline:
# backup & reset readline completer
old_readline_completer = readline.get_completer()
readline.set_completer((lambda x: x))
# backup & reset readline history
old_readline_history = []
hist_sz = readline.get_current_history_length()
for i in range(1, hist_sz + 1):
line = readline.get_history_item(i)
old_readline_history.append(line)
readline.clear_history()
try:
retval = function(*args, **kwargs)
finally:
if handle_readline:
# restore old readline completer
readline.set_completer(old_readline_completer)
# restore old readline history
readline.clear_history()
for line in old_readline_history:
readline.add_history(line)
return retval
示例13: edit_attr
def edit_attr(dict, attr):
"""Edits an attribute in the dictionary dict."""
completer = readline.get_completer()
readline.set_completer(None)
current_value = dict[attr]
try:
print "\n# Documentation: %s" % dict[attr + "_doc"]
except:
pass
print "# Current value: %s = %s" % (attr, str(current_value))
while True:
new_value = raw_input("# New value: %s = " % attr)
if new_value == "":
new_value = current_value
print "# Using the current value (%s)" % str(current_value)
break
try:
new_value = double(new_value) # try interpreting as a number
except:
pass # leave as a string
break
readline.set_completer(completer)
return new_value
示例14: loop
def loop(self):
previous_completer = readline.get_completer()
readline.parse_and_bind("tab: complete")
readline.set_completer(self.walk)
prompt = self.prompt + self.prompt_delim
if not ishell._current_prompt:
previous_prompt = prompt
else:
previous_prompt = ishell._current_prompt
ishell._current_prompt = prompt
if self.welcome_message:
sys.stdout.write(self.welcome_message + "\n\r")
while 1:
try:
sys.stdout.write("\r")
if self._exit:
break
sys.stdout.write("\033[K")
input_ = input(prompt + " ")
if not input_.strip():
self.print_childs_help()
elif input_ in ('quit', 'exit'):
break
else:
self.walk_and_run(input_)
except (KeyboardInterrupt, EOFError):
print("exit")
break
except Exception:
print(traceback.format_exc())
sys.exit(1)
ishell._current_prompt = previous_prompt
readline.set_completer(previous_completer)
示例15: rlinput
def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
"""
Get user input with readline editing support.
"""
sentinel = ''
if prefill is None:
prefill = ''
def only_once(text):
""" generator for startup hook """
readline.insert_text(text)
yield
while True:
yield
savedhist = NamedTemporaryFile()
readline.write_history_file(savedhist.name)
ctxhistname = ".tl" + ctxkey + "history"
ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
try:
readline.clear_history()
except AttributeError:
print "This readline doesn't support clear_history()"
raise
savedcompleter = readline.get_completer()
try:
ulines = uniqify(ctxhistfile)
readline.read_history_file(ctxhistfile)
readline.set_completer(HistoryCompleter(ulines).complete)
except IOError:
pass
readline.parse_and_bind('tab: complete')
saveddelims = readline.get_completer_delims()
readline.set_completer_delims('') ## No delims. Complete entire lines.
readline.set_completion_display_matches_hook(match_display_hook)
gen = only_once(prefill)
readline.set_startup_hook(gen.next)
try:
if oneline:
edited = raw_input(prompt)
else:
print prompt
edited = "\n".join(iter(raw_input, sentinel))
if edited.endswith(r'%%'):
## Invoke external editor
edited = external_edit(edited[0:-2])
return edited
finally:
## Restore readline state
readline.write_history_file(ctxhistfile)
readline.clear_history()
readline.read_history_file(savedhist.name)
savedhist.close()
readline.set_completer(savedcompleter)
readline.set_completer_delims(saveddelims)
readline.set_startup_hook()