本文整理汇总了Python中readline.set_completer函数的典型用法代码示例。如果您正苦于以下问题:Python set_completer函数的具体用法?Python set_completer怎么用?Python set_completer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了set_completer函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: runInteractive
def runInteractive(locals):
prompt = "ToMaTo"
import readline, rlcompleter, code
readline.parse_and_bind("tab: complete")
readline.set_completer(rlcompleter.Completer(locals).complete)
console = code.InteractiveConsole(locals)
console.interact('Type "help()" or "help(method)" for more information.')
开发者ID:david-hock,项目名称:ToMaTo,代码行数:7,代码来源:tomato.py
示例2: run_plain
def run_plain():
# Using normal Python shell
import code
imported_objects = import_objects(options, self.style)
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 import user.
if use_pythonrc:
pythonrc = os.environ.get("PYTHONSTARTUP")
if pythonrc and os.path.isfile(pythonrc):
global_ns = {}
with open(pythonrc) as rcfile:
try:
six.exec_(compile(rcfile.read(), pythonrc, 'exec'), global_ns)
imported_objects.update(global_ns)
except NameError:
pass
# This will import .pythonrc.py as a side-effect
try:
import user # NOQA
except ImportError:
pass
code.interact(local=imported_objects)
开发者ID:JamesX88,项目名称:tes,代码行数:34,代码来源:shell_plus.py
示例3: 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)
开发者ID:gadeleon,项目名称:pwman3,代码行数:7,代码来源:tools.py
示例4: __init__
def __init__(self,on_kill=None,*args,**kw):
code.InteractiveConsole.__init__(self,*args,**kw)
self.code_to_run = None
self.ready = threading.Condition()
self._kill = False
if on_kill is None:
on_kill = []
# Check that all things to kill are callable:
for _ in on_kill:
if not callable(_):
raise TypeError,'on_kill must be a list of callables'
self.on_kill = on_kill
# Set up tab-completer
if has_readline:
import rlcompleter
try: # this form only works with python 2.3
self.completer = rlcompleter.Completer(self.locals)
except: # simpler for py2.2
self.completer = rlcompleter.Completer()
readline.set_completer(self.completer.complete)
# Use tab for completions
readline.parse_and_bind('tab: complete')
# This forces readline to automatically print the above list when tab
# completion is set to 'complete'.
readline.parse_and_bind('set show-all-if-ambiguous on')
# Bindings for incremental searches in the history. These searches
# use the string typed so far on the command line and search
# anything in the previous input history containing them.
readline.parse_and_bind('"\C-r": reverse-search-history')
readline.parse_and_bind('"\C-s": forward-search-history')
开发者ID:NICKLAB,项目名称:matplotlib,代码行数:31,代码来源:interactive.py
示例5: cmdloop
def cmdloop(self, intro=None):
self.old_completer = readline.get_completer()
self.old_completer_delims = readline.get_completer_delims()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey+": complete")
readline.parse_and_bind("set bell-style none")
readline.parse_and_bind("set show-all-if-ambiguous")
readline.parse_and_bind("set completion-query-items -1")
# If press help key, add the character and accept the line
readline.parse_and_bind('"?": "\C-q?\C-j"')
# Register a function for execute before read user
# input. We can use it for insert text at command line
readline.set_pre_input_hook(self.pre_input_hook)
readline.set_completer_delims(' \t\n')
try:
stop = None
while not stop:
try:
line = raw_input(self.prompt)
except EOFError:
line = 'EOF'
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
finally:
readline.set_completer(self.old_completer)
readline.set_completer_delims(self.old_completer_delims)
开发者ID:aleasoluciones,项目名称:boscli-oss-core,代码行数:29,代码来源:boscli.py
示例6: interactive_browser
def interactive_browser(srcdir=None):
"""
launch an interactive view for browsing the original
archives.
"""
info("launching interactive data browser...")
# the variable is actually used, in the interactive prompt.
# pylint: disable=unused-variable
data, game_versions = mount_input(srcdir)
if not data:
warn("cannot launch browser as no valid input assets were found.")
return
def save(path, target):
"""
save a path to a custom target
"""
with path.open("rb") as infile:
with open(target, "rb") as outfile:
outfile.write(infile.read())
def save_slp(path, target, palette=None):
"""
save a slp as png.
"""
from .texture import Texture
from .slp import SLP
from .driver import get_palette
if not palette:
palette = get_palette(data, game_versions)
with path.open("rb") as slpfile:
tex = Texture(SLP(slpfile.read()), palette)
out_path, filename = os.path.split(target)
tex.save(Directory(out_path).root, filename)
import code
from pprint import pprint
import rlcompleter
completer = rlcompleter.Completer(locals())
readline.parse_and_bind("tab: complete")
readline.parse_and_bind("set show-all-if-ambiguous on")
readline.set_completer(completer.complete)
code.interact(
banner=("\nuse `pprint` for beautiful output!\n"
"you can access stuff by the `data` variable!\n"
"`data` is an openage.util.fslike.path.Path!\n"
"* list contents: `pprint(list(data['graphics'].list()))`\n"
"* dump data: `save(data['file/path'], '/tmp/outputfile')`.\n"
"* save a slp as png: `save_slp(data['dir/123.slp'], '/tmp/pic.png')`.\n"),
local=locals()
)
开发者ID:Jineapple,项目名称:openage,代码行数:60,代码来源:main.py
示例7: interactive_argument_resolver
def interactive_argument_resolver(parser):
input_strings = []
# Iterate through all arguments in the parser
for action in [a for a in parser.__dict__['_actions'] if a.nargs is not 0]:
# Use the rightmost defined flag
flag = action.option_strings[-1]
# Iterate until input value is accepted
while True:
# Set an auto completer if choices are defined
if action.choices:
readline.set_completer(_make_autocompleter(action.choices))
# Clear the auto completer otherwise
else:
readline.set_completer(_make_autocompleter(['']))
# Prompt user for an input value
value = raw_input(_prompt(action))
# If user input is blank and there is a default value defined, use the default value
if not value and action.default:
value = action.default
break
# If user input validates
if _value_validates(action, value):
break
# Add flag and value to resulting list of arguments
input_strings.append(flag)
input_strings.append(value)
return parser.parse_args(input_strings)
开发者ID:runarfu,项目名称:interactive-argparse,代码行数:32,代码来源:interactive_argparse.py
示例8: plain
def plain(self):
"""Plain Python shell."""
from nikola import Nikola
try:
import conf
SITE = Nikola(**conf.__dict__)
SITE.scan_posts()
gl = {'conf': conf, 'SITE': SITE, 'Nikola': Nikola}
except ImportError:
LOGGER.error("No configuration found, cannot run the console.")
else:
import code
try:
import readline
except ImportError:
pass
else:
import rlcompleter
readline.set_completer(rlcompleter.Completer(gl).complete)
readline.parse_and_bind("tab:complete")
pythonrc = os.environ.get("PYTHONSTARTUP")
if pythonrc and os.path.isfile(pythonrc):
try:
execfile(pythonrc) # NOQA
except NameError:
pass
code.interact(local=gl, banner=self.header.format('Python'))
开发者ID:ermeaney,项目名称:nikola,代码行数:29,代码来源:console.py
示例9: completer
def completer(self,func):
def keys():
keys = [i for i in func()]
return keys
readline.set_completer(SimpleCompleter(keys()).complete)
readline.set_completer_delims('')
readline.parse_and_bind('tab: complete')
开发者ID:kheodan,项目名称:examples,代码行数:7,代码来源:examples.py
示例10: handle
def handle(self, **options):
imported_objects = {}
try:
from django.db.models.loading import get_models
except ImportError:
from django.apps import apps
get_models = apps.get_models
for m in get_models():
imported_objects[m.__name__] = m
try:
self.ipython(imported_objects)
except ImportError:
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'
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(
rlcompleter.Completer(imported_objects).complete)
readline.parse_and_bind("tab:complete")
code.interact(local=imported_objects)
开发者ID:ngkabra,项目名称:dutils,代码行数:26,代码来源:shell+.py
示例11: sshcheck
def sshcheck():
attacks = {}
users = {}
try:
import readline, rlcompleter
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
except ImportError:
print 'No Tab Completion'
LOGs = raw_input('Enter the path to the log file: ')
for LOG in LOGs.split(' '):
if LOG.endswith('.gz'):
auth_logs = gzip.GzipFile(LOG, 'r')
else:
auth_logs = open(LOG, 'r')
if len(LOGs) is '1':
print "Parsing log file"
else:
print "Parsing log files"
for log in auth_logs:
l = {"raw": log }
normalizer.normalize(l)
if l.get('action') == 'fail' and l.get('program') == 'sshd':
u = l['user']
p = l['source_ip']
o1, o2, o3, o4 = [int(i) for i in p.split('.')]
if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10:
print "Private IP, %s No geolocation data" %str(p)
attacks[p] = attacks.get(p, 0) + 1
getip()
dojson(attacks, IP)
开发者ID:radman404,项目名称:Who-s-attacking-me-now--,代码行数:32,代码来源:wamnclient.py
示例12: 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()
开发者ID:Michael-F-Ellis,项目名称:TransLily,代码行数:60,代码来源:rl_interface.py
示例13: __init__
def __init__(self, locals=None, filename="<console>",
session = session,
request_socket=None,
sub_socket=None):
code.InteractiveConsole.__init__(self, locals, filename)
self.session = session
self.request_socket = request_socket
self.sub_socket = sub_socket
self.backgrounded = 0
self.messages = {}
# Set tab completion
self.completer = completer.ClientCompleter(self, session, request_socket)
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set show-all-if-ambiguous on')
readline.set_completer(self.completer.complete)
# Set system prompts
sys.ps1 = 'Py>>> '
sys.ps2 = ' ... '
sys.ps3 = 'Out : '
# Build dict of handlers for message types
self.handlers = {}
for msg_type in ['pyin', 'pyout', 'pyerr', 'stream']:
self.handlers[msg_type] = getattr(self, 'handle_%s' % msg_type)
开发者ID:GunioRobot,项目名称:pyzmq,代码行数:25,代码来源:frontend.py
示例14: setup
def setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
if not os.path.exists(self.history_file):
with open(self.history_file, 'a+') as history:
if is_libedit():
history.write("_HiStOrY_V2_\n\n")
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;')
if is_libedit():
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
开发者ID:zongdeiqianxing,项目名称:routersploit,代码行数:25,代码来源:interpreter.py
示例15: uninit_completer
def uninit_completer(self):
try:
import readline
readline.set_completer()
readline.clear_history()
except:
pass
开发者ID:kedarmhaswade,项目名称:dx-toolkit,代码行数:7,代码来源:exec_io.py
示例16: get_input_with_readline
def get_input_with_readline(filename):
"""
sets up readline support for entering sitenames, completed from the
existing list and accepts a line of input.
"""
if not os.path.exists(filename):
file(filename, "w").close()
all_lines = map(lambda x: x.strip(), file(filename).readlines())
def completer(text, state):
"""
custom readline completer
"""
candidates = filter(lambda x: x.startswith(text), all_lines)
if state <= len(candidates):
return candidates[state-1]
else:
return None
try:
import readline
readline.set_completer(completer)
readline.read_history_file(filename)
readline.parse_and_bind('tab: complete')
if hasattr(readline, 'readline'):
print "sitename: ",
readline._issued = True
return readline.readline(history=all_lines, histfile=None)
else:
return raw_input("sitename: ")
except:
# no readline?
return raw_input("sitename: ")
开发者ID:gera,项目名称:spg,代码行数:34,代码来源:__init__.py
示例17: __init__
def __init__(self, inp=None, out=None, opts={}):
get_option = lambda key: Mmisc.option_set(opts, key,
DEFAULT_USER_SETTINGS)
Minput = import_relative('input', '..inout', 'trepan')
Moutput = import_relative('output', '..inout', 'trepan')
atexit.register(self.finalize)
self.interactive = True # Or at least so we think initially
self.input = inp or Minput.DebuggerUserInput()
self.output = out or Moutput.DebuggerUserOutput()
if self.input.use_history():
complete = get_option('complete')
if complete:
parse_and_bind("tab: complete")
set_completer(complete)
pass
self.histfile = get_option('histfile')
if self.histfile:
try:
read_history_file(histfile)
except IOError:
pass
set_history_length(50)
atexit.register(write_history_file, self.histfile)
pass
return
开发者ID:msabramo,项目名称:python2-trepan,代码行数:28,代码来源:user.py
示例18: FastLogin
def FastLogin(self):
data = map(str, DBQuery().AuthIP())
ip_user = [v.replace('\t', ' ') for v in data]
# raw_input tab
def complete(text, state):
for i in ip_user:
if i.startswith(text):
if not state:
return i
else:
state -= 1
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
while True:
ip_user = raw_input('Please input ip and user > ').strip().split()
if 'q' in ip_user:
self.Main()
elif len(ip_user) == 2:
remote_ip, remote_user = ip_user[0], ip_user[1]
self.Connection(remote_ip, remote_user)
break
else:
continue
开发者ID:Cnlouds,项目名称:triaquae,代码行数:25,代码来源:baoleicmd.py
示例19: __init__
def __init__(self):
self.sentCache = {}
self.commands = {}
self.acceptingInput = False
self.lastPrompt = True
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:],
"desc": fn.clidesc,
"fn": fn,
"order": fn.cliorder
}
self.cv = threading.Condition()
self.inputThread = threading.Thread(target = self.startInputThread, args = (self.cv,))
self.inputThread.daemon = True
开发者ID:jonnieluv,项目名称:yowsup,代码行数:35,代码来源:cli.py
示例20: main
def main():
global __prompt
global __time_to_go
print("JSON configuration utility version (1.0.0)")
handle_arguments()
readline.set_completer_delims("\t\n")
readline.parse_and_bind("tab: complete")
readline.set_completer(auto_complete)
command = ""
while True:
try:
user_input = input(__prompt + " ").strip()
except KeyboardInterrupt:
print()
if __time_to_go:
exit_command()
else:
__time_to_go = True
print("Press ^C again to close. Running another command resets this.")
continue
if not user_input:
continue
run_command(user_input)
__time_to_go = False
开发者ID:Riobe,项目名称:dot-pyson,代码行数:29,代码来源:dot-pyson.py
注:本文中的readline.set_completer函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论