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 :-(')
python类get_completer_delims()的实例源码
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 cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
def cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
def cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
def cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
def cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
def cmdloop_with_history(self):
"""
Better command loop, with history file and tweaked readline
completion delimiters.
"""
old_completer_delims = readline.get_completer_delims()
if self.histfile is not None:
try:
readline.read_history_file(self.histfile)
except IOError:
pass
try:
readline.set_completer_delims("".join(set(old_completer_delims) - set(self.identchars)))
self.cmdloop()
finally:
if self.histfile is not None and readline.get_current_history_length():
readline.write_history_file(self.histfile)
readline.set_completer_delims(old_completer_delims)
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 __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 test_context_manager_with_unmocked_readline(self):
from certbot.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)
def __init__(self, p):
super(readkbd, self).__init__(p)
self.prompt = p
self.controlc = None
# we want readline completer to give us the "/" as well!
readline.set_completer_delims( readline.get_completer_delims().replace("/", "").replace("-","") )
print "+++++++++++++++++++++ Welcome to cli +++++++++++++++++++"
print "$Id: command.py,v 1.16 2015-11-04 13:30:10 jive_cc Exp $"
print " 'exit' exits, 'list' lists, 'help' helps "
# add the iterator protocol (the context protocol is supplied by newhistory)
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 test_context_manager_with_unmocked_readline(self):
from certbot.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)
def get_completer_delims(self):
"""
Get the completer delimiters--the characters that delimit tokens
that are eligible for completion.
:rtype: str
:return: the delimiters
"""
return ''
def get_completer_delims(self,):
return readline.get_completer_delims()
def get_completer_delims(self):
return readline.get_completer_delims()
def complete_set(self, text, line, begidx, endidx):
""" Provide completion for the "set" option
Autocomplete the option name and append a "="
Autocomplete accessible random value generators
available for the concerned parameter.
"""
# complete with available options - suppose only one =, no spaces
if "=" in line:
option_name, arg_typed = line[line.find(' ')+1:].split("=")
l = self._module_inst.get_possible_values(option_name, arg_typed)
last_completer_delim_index = -1
for delim in readline.get_completer_delims():
last_completer_delim_index = max(last_completer_delim_index, arg_typed.rfind(delim))
return [
val
for val in l
if self._module_inst.is_a_valid_value_for_this_option(
option_name, arg_typed[:last_completer_delim_index+1] + val
)
]
else:
return [
'{}='.format(i)
for i in type(self._module_inst).get_option_list()
if i.startswith(text)
]
def launch_ui(args):
# Setup tab completion
try:
import readline
except ImportError:
print('%s[!] Module \'readline\' not available. Tab complete disabled.%s' % (Colors.R, Colors.N))
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(re.sub('[/-]', '', readline.get_completer_delims()))
# Instantiate the UI object
x = cli.CLI(cli.Mode.CONSOLE)
# check for and run version check
if args.check:
if not x.version_check(): return
# Check for and run script session
if args.script_file:
x.do_resource(args.script_file)
# Run the UI
try:
x.cmdloop()
except KeyboardInterrupt:
print('')
# ======================================================================================================================
# MAIN
# ======================================================================================================================
def __init__(self,cmdcomplete,init_flag=True):
self.text = ""
self.matches = []
self.cmdcomplete = cmdcomplete
self.symbols = []
self.index = 0
self.cleanup_flag = True
self.init_flag = init_flag
self.session_start_index = 0
self.HISTLEN = 2000
self.HISTFILE = ".atrophy-history"
self.DEFAULT_HIST_DISPLAY_LEN = 20
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("/",''))
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("?",''))
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("@",''))
readline.parse_and_bind('tab: complete')
readline.set_completer(self.complete)
# persistant commands that actually affect a session
# (e.g. breakpoints, mem writes, comments)
self.project_cmds = [ "sd", "b", "db", "sb","#", "//" ]
if self.init_flag == True:
self.init_flag = False
try:
readline.read_history_file(self.HISTFILE)
self.session_start_index = readline.get_current_history_length()
readline.set_history_length(self.HISTLEN)
except Exception as e:
pass
atexit.register(self.on_exit,self.HISTFILE)
def preloop(self):
delims = set(readline.get_completer_delims())
for d in "%*-/":
try:
delims.remove(d)
except KeyError:
pass
readline.set_completer_delims(''.join(delims))
try:
readline.read_history_file(self.HISTORY_FILE)
except (OSError, IOError) as e:
warn("Can't read history file")
def _cmdloop(self):
"""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.
This serves the same role as cmd.cmdloop().
:return: bool - True implies the entire application should exit.
"""
# An almost perfect copy from Cmd; however, the pseudo_raw_input portion
# has been split out so that it can be called separately
if self.use_rawinput and self.completekey:
try:
self.old_completer = readline.get_completer()
self.old_delims = readline.get_completer_delims()
readline.set_completer(self.complete)
# Don't treat "-" as a readline delimiter since it is commonly used in filesystem paths
readline.set_completer_delims(self.old_delims.replace('-', ''))
readline.parse_and_bind(self.completekey + ": complete")
except NameError:
pass
stop = None
try:
while not stop:
if self.cmdqueue:
# Run command out of cmdqueue if nonempty (populated by load command or commands at invocation)
line = self.cmdqueue.pop(0)
if self.echo and line != 'eos':
self.poutput('{}{}'.format(self.prompt, line))
else:
# Otherwise, read a command from stdin
line = self.pseudo_raw_input(self.prompt)
# Run the command along with all associated pre and post hooks
stop = self.onecmd_plus_hooks(line)
finally:
if self.use_rawinput and self.completekey:
try:
readline.set_completer(self.old_completer)
readline.set_completer_delims(self.old_delims)
except NameError:
pass
# Need to set empty list this way because Python 2 doesn't support the clear() method on lists
self.cmdqueue = []
self._script_dir = []
return stop
# noinspection PyUnusedLocal
def run_interactive_gtp_session(engine):
"""Run a GTP engine session on stdin and stdout, using readline.
engine -- Gtp_engine_protocol object
This enables readline tab-expansion, and command history in
~/.gomill-gtp-history (if readline is available).
Returns either when EOF is seen on stdin, or when the engine signals end of
session.
If stdin isn't a terminal, this is equivalent to run_gtp_session.
If a write fails with 'broken pipe', this raises ControllerDisconnected.
Note that this will propagate KeyboardInterrupt if the user presses ^C;
normally you'll want to handle this to avoid an ugly traceback.
"""
# readline doesn't do anything if stdin isn't a tty, but it's simplest to
# just not import it in that case.
try:
use_readline = os.isatty(sys.stdin.fileno())
if use_readline:
import readline
except Exception:
use_readline = False
if not use_readline:
run_gtp_session(engine, sys.stdin, sys.stdout)
return
def write(s):
sys.stdout.write(s)
sys.stdout.flush()
history_pathname = os.path.expanduser("~/.gomill-gtp-history")
readline.parse_and_bind("tab: complete")
old_completer = readline.get_completer()
old_delims = readline.get_completer_delims()
readline.set_completer(make_readline_completer(engine))
readline.set_completer_delims("")
try:
readline.read_history_file(history_pathname)
except EnvironmentError:
pass
_run_gtp_session(engine, raw_input, write)
try:
readline.write_history_file(history_pathname)
except EnvironmentError:
pass
readline.set_completer(old_completer)
readline.set_completer_delims(old_delims)