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)
python类parse_and_bind()的实例源码
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 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 read_storage_path_from_prompt():
readline.set_completer_delims(' \t\n')
readline.parse_and_bind("tab: complete")
choice = input('Set storage directory [Enter for "%s"]: ' % DEFAULT_STORAGE)
return choice or DEFAULT_STORAGE
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 _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 run(self, shell=None):
"""Runs a Python interactive interpreter."""
if not shell:
shell = 'bpython'
if shell == 'bpython':
try:
import bpython
bpython.embed()
except ImportError:
shell = 'ipython'
if shell == 'ipython':
try:
from IPython import embed
embed()
except ImportError:
# Ipython < 0.11
try:
import IPython
# Explicitly pass an empty list as arguments, because
# otherwise IPython would use sys.argv from this script.
shell = IPython.Shell.IPShell(argv=[])
shell.mainloop()
except ImportError:
# no IPython module
shell = 'python'
if shell == 'python':
import code
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 # noqa
readline.parse_and_bind("tab:complete")
code.interact()
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 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 __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_mock_readline(self, mock_readline):
from certbot.display import completer
mock_readline.parse_and_bind.side_effect = enable_tab_completion
with completer.Completer():
pass
self.assertTrue(mock_readline.parse_and_bind.called)
def enable_tab_completion(unused_command):
"""Enables readline tab completion using the system specific syntax."""
libedit = 'libedit' in readline.__doc__
command = 'bind ^I rl_complete' if libedit else 'tab: complete'
readline.parse_and_bind(command)