Python源码示例:rlcompleter.Completer()
示例1
def run_console(glob):
import readline
import rlcompleter
import atexit
import code
history_path = os.path.expanduser("~/.python_history")
def save_history(history_path=history_path):
readline.write_history_file(history_path)
if os.path.exists(history_path):
readline.read_history_file(history_path)
atexit.register(save_history)
readline.set_completer(rlcompleter.Completer(glob).complete)
readline.parse_and_bind("tab: complete")
code.InteractiveConsole(locals=glob).interact()
示例2
def complete(self, text, state):
if state == 0:
self.completions = []
append = self.completions.append
for path in glob.glob(text + '*'):
if os.path.isdir(path):
if not path.endswith(os.sep):
path += os.sep
else:
path += ' '
append(path)
pycompleter = rlcompleter.Completer(namespace=self.local).complete
for i in count():
completion = pycompleter(text, i)
if completion is None:
break
else:
append(completion)
try:
return self.completions[state]
except IndexError:
return None
示例3
def test_main():
support.run_unittest(TestRlcompleter)
def test_duplicate_globals(self):
namespace = {
'False': None, # Keyword vs builtin vs namespace
'assert': None, # Keyword vs namespace
'try': lambda: None, # Keyword vs callable
'memoryview': None, # Callable builtin vs non-callable
'Ellipsis': lambda: None, # Non-callable builtin vs callable
}
completer = rlcompleter.Completer(namespace)
self.assertEqual(completer.complete('False', 0), 'False')
self.assertIsNone(completer.complete('False', 1)) # No duplicates
self.assertEqual(completer.complete('assert', 0), 'assert')
self.assertIsNone(completer.complete('assert', 1))
self.assertEqual(completer.complete('try', 0), 'try')
self.assertIsNone(completer.complete('try', 1))
# No opening bracket "(" because we overrode the built-in class
self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
self.assertIsNone(completer.complete('memoryview', 1))
self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
self.assertIsNone(completer.complete('Ellipsis', 1))
示例4
def complete_names(word, namespace):
"""Complete variable names or attributes
:param word: word to be completed
:type word: str
:param namespace: namespace
:type namespace: dict
:returns: completion matches
:rtype: list of str
>>> complete_names('fo', {'foo': 'bar'})
['foo', 'for', 'format(']
"""
# start completer
completer = rlcompleter.Completer(namespace)
# find matches with std library (don't try to implement this yourself)
completer.complete(word, 0)
return sorted(set(completer.matches))
示例5
def test_duplicate_globals(self):
namespace = {
'False': None, # Keyword vs builtin vs namespace
'assert': None, # Keyword vs namespace
'try': lambda: None, # Keyword vs callable
'memoryview': None, # Callable builtin vs non-callable
'Ellipsis': lambda: None, # Non-callable builtin vs callable
}
completer = rlcompleter.Completer(namespace)
self.assertEqual(completer.complete('False', 0), 'False')
self.assertIsNone(completer.complete('False', 1)) # No duplicates
self.assertEqual(completer.complete('assert', 0), 'assert')
self.assertIsNone(completer.complete('assert', 1))
self.assertEqual(completer.complete('try', 0), 'try')
self.assertIsNone(completer.complete('try', 1))
# No opening bracket "(" because we overrode the built-in class
self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
self.assertIsNone(completer.complete('memoryview', 1))
self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
self.assertIsNone(completer.complete('Ellipsis', 1))
示例6
def test_duplicate_globals(self):
namespace = {
'False': None, # Keyword vs builtin vs namespace
'assert': None, # Keyword vs namespace
'try': lambda: None, # Keyword vs callable
'memoryview': None, # Callable builtin vs non-callable
'Ellipsis': lambda: None, # Non-callable builtin vs callable
}
completer = rlcompleter.Completer(namespace)
self.assertEqual(completer.complete('False', 0), 'False')
self.assertIsNone(completer.complete('False', 1)) # No duplicates
self.assertEqual(completer.complete('assert', 0), 'assert')
self.assertIsNone(completer.complete('assert', 1))
self.assertEqual(completer.complete('try', 0), 'try')
self.assertIsNone(completer.complete('try', 1))
# No opening bracket "(" because we overrode the built-in class
self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
self.assertIsNone(completer.complete('memoryview', 1))
self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
self.assertIsNone(completer.complete('Ellipsis', 1))
示例7
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)
示例8
def start(self) -> None:
try:
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(self.context).complete)
readline.parse_and_bind("tab:complete")
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn("Custom output templates not supported by PythonShell.")
code.interact(self.banner, local=self.context)
return None
示例9
def run_client(host="localhost", port=9901):
import code
import readline
import rlcompleter
url = "http://{host}:{port}/jsonrpc".format(host=host, port=port)
cli = TeleniumHttpClient(url=url, timeout=5)
print("Connecting to {}".format(url))
while not cli.ping():
sleep(.1)
print("Connected!")
vars = globals()
vars.update(locals())
readline.set_completer(rlcompleter.Completer(vars).complete)
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole(vars)
shell.interact()
示例10
def setupReadline(local):
"""Initialize the readline library and command history.
@return: A C{bool} to indicate whether standard input is a terminal
(and therefore interactive).
"""
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(' \t\n')
readline.set_completer(Completer(local).complete)
# Readline code from https://docs.python.org/3.7/library/readline.html
histfile = os.path.join(os.path.expanduser('~'), '.daudin_history')
try:
readline.read_history_file(histfile)
historyLen = readline.get_current_history_length()
except FileNotFoundError:
open(histfile, 'wb').close()
historyLen = 0
try:
readline.append_history_file
except AttributeError:
# We won't be able to save readline history. This can happen on
# Python 3.5 at least - not sure why.
pass
else:
import atexit
def saveHistory(prevHistoryLen, histfile):
newHistoryLen = readline.get_current_history_length()
readline.set_history_length(1000)
readline.append_history_file(newHistoryLen - prevHistoryLen,
histfile)
atexit.register(saveHistory, historyLen, histfile)
return True
示例11
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)
示例12
def __exec_py(self, args):
ns = {"api": self.api, "args": args[1:], "analyzer": self.analyzer}
ns.update(EXPORTED_SYMBOLS)
if len(args) > 1:
if args[1].startswith("!"):
args[1] = "%s/%s" % (PLASMA_SCRIPTS_DIR, args[1][1:])
exec(open(args[1]).read(), ns)
else:
readline.set_completer(rlcompleter.Completer(ns).complete)
code.interact(local=ns)
readline.set_completer(self.comp.complete)
示例13
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
示例14
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))
示例15
def test_excessive_getattr(self):
# Ensure getattr() is invoked no more than once per attribute
class Foo:
calls = 0
@property
def bar(self):
self.calls += 1
return None
f = Foo()
completer = rlcompleter.Completer(dict(f=f))
self.assertEqual(completer.complete('f.b', 0), 'f.bar')
self.assertEqual(f.calls, 1)
示例16
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
示例17
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))
示例18
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
示例19
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))
示例20
def global_matches( self, text ):
matches = rlcompleter.Completer.global_matches( self, text )
if not matches: matches = []
matches += self.file_matches( text )
return matches
示例21
def attr_matches( self, text ):
matches = rlcompleter.Completer.attr_matches( self, text )
if not matches: matches = []
b = text.find('.')
try:
if 0 <= b and self.namespace[text[:b]].__name__ == 'ROOT':
matches += self.root_global_matches( text[b+1:], text[:b+1] )
except AttributeError: # not all objects have a __name__
pass
return matches
示例22
def _main_import_interactive(project, origin, args):
from .contrib.import_export import _prepare_import_into_project
if args.move:
raise ValueError("Cannot use '--move' in combination with '--sync-interactive'.")
with project.temporary_project() as tmp_project:
_print_err("Prepare data space for import...")
with _prepare_import_into_project(origin, tmp_project, args.schema_path) as data_mapping:
paths = dict()
for src, copy_executor in tqdm(
dict(data_mapping).items(), desc='Import to temporary project'):
paths[src] = copy_executor()
local_ns = dict(
signac=importlib.import_module(__package__),
project=project, pr=project,
tmp_project=tmp_project)
if READLINE:
readline.set_completer(Completer(local_ns).complete)
readline.parse_and_bind('tab: complete')
code.interact(
local=local_ns,
banner=SHELL_BANNER_INTERACTIVE_IMPORT.format(
python_version=sys.version,
signac_version=__version__,
project_id=project.get_id(),
job_banner='',
root_path=project.root_directory(),
workspace_path=project.workspace(),
size=len(project),
origin=args.origin))
return paths
示例23
def run_python(local):
import code
try:
import readline
except ImportError:
pass
else:
import rlcompleter
readline.set_completer(rlcompleter.Completer(local).complete)
readline.parse_and_bind('tab:complete')
code.interact(local=local)
示例24
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
示例25
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))
示例26
def test_excessive_getattr(self):
# Ensure getattr() is invoked no more than once per attribute
class Foo:
calls = 0
@property
def bar(self):
self.calls += 1
return None
f = Foo()
completer = rlcompleter.Completer(dict(f=f))
self.assertEqual(completer.complete('f.b', 0), 'f.bar')
self.assertEqual(f.calls, 1)
示例27
def test_complete(self):
completer = rlcompleter.Completer()
self.assertEqual(completer.complete('', 0), '\t')
self.assertEqual(completer.complete('a', 0), 'and')
self.assertEqual(completer.complete('a', 1), 'as')
self.assertEqual(completer.complete('as', 2), 'assert')
self.assertEqual(completer.complete('an', 0), 'and')
示例28
def _enable_completer(context=None):
try:
import readline
except ImportError:
return
try:
import rlcompleter
except ImportError:
return
readline.set_completer(rlcompleter.Completer(context).complete)
readline.parse_and_bind("tab:complete")
# command history
if os.path.exists(HISTORY_PATH):
readline.read_history_file(HISTORY_PATH)
atexit.register(_save_history)
示例29
def setUp(self):
self.stdcompleter = rlcompleter.Completer()
self.completer = rlcompleter.Completer(dict(spam=int,
egg=str,
CompleteMe=CompleteMe))
# forces stdcompleter to bind builtins namespace
self.stdcompleter.complete('', 0)
示例30
def test_namespace(self):
class A(dict):
pass
class B(list):
pass
self.assertTrue(self.stdcompleter.use_main_ns)
self.assertFalse(self.completer.use_main_ns)
self.assertFalse(rlcompleter.Completer(A()).use_main_ns)
self.assertRaises(TypeError, rlcompleter.Completer, B((1,)))