本文整理汇总了Python中readline.parse_and_bind函数的典型用法代码示例。如果您正苦于以下问题:Python parse_and_bind函数的具体用法?Python parse_and_bind怎么用?Python parse_and_bind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_and_bind函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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)
示例2: run_classic_shell
def run_classic_shell(locals, globals, first_time):
if first_time:
banner = "Hit Ctrl-D to return to PuDB."
else:
banner = ""
ns = SetPropagatingDict([locals, globals], locals)
from pudb.settings import get_save_config_path
from os.path import join
hist_file = join(
get_save_config_path(),
"shell-history")
if HAVE_READLINE:
readline.set_completer(
rlcompleter.Completer(ns).complete)
readline.parse_and_bind("tab: complete")
try:
readline.read_history_file(hist_file)
except IOError:
pass
from code import InteractiveConsole
cons = InteractiveConsole(ns)
cons.interact(banner)
if HAVE_READLINE:
readline.write_history_file(hist_file)
示例3: register_readline
def register_readline():
import atexit
try:
import readline
import rlcompleter
except ImportError:
return
# Reading the initialization (config) file may not be enough to set a
# completion key, so we set one first and then read the file
if 'libedit' in getattr(readline, '__doc__', ''):
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
try:
readline.read_init_file()
except OSError:
# An OSError here could have many causes, but the most likely one
# is that there's no .inputrc file (or .editrc file in the case of
# Mac OS X + libedit) in the expected location. In that case, we
# want to ignore the exception.
pass
history = os.path.join(os.path.expanduser('~'), '.python_history')
try:
readline.read_history_file(history)
except IOError:
pass
atexit.register(readline.write_history_file, history)
示例4: init_readline
def init_readline(self):
init_file = os.path.expanduser("~/.%s-init" % self.__name)
readline.parse_and_bind("set bell-style visible")
try:
readline.read_init_file(init_file)
except IOError:
pass
示例5: 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()
)
示例6: file_chooser
def file_chooser(prompt_text = "Enter File: ", default=None, filearg=[], filekwarg={}):
"""A simple tool to get a file from the user. Takes keyworded arguemnts
and passes them to open().
If the user enters nothing the function will return the ``default`` value.
Otherwise it continues to prompt the user until it get's a decent response.
filekwarg may contain arguements passed on to ``open()``.
"""
try:
import readline, rlcomplete
completer = rlcomplete.PathCompleter()
readline.set_completer_delims(completer.delims)
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
except ImportError:
pass
while True:
f = raw_input(prompt_text)
if f == '': return default
f = os.path.expanduser(f)
if len(f) != 0 and f[0] == os.path.sep:
f = os.path.abspath(f)
try:
return open(f, *filearg, **filekwarg)
except IOError, e:
stderr.write(ERROR_MESSAGE % ("unable to open %s : %s" % (f, e)))
示例7: shell
def shell(vars, message="Entering Interactive Python Interpreter",
prompt="(py)pylans:>", exit_msg="Returning to pylans cli"):
'''
Start an interactive (i)python interpreter on the commandline.
This blocks, so don't call from twisted, but in a thread or from Cmd is fine.
:param vars: variables to make available to interpreter
:type vars: dict
'''
try:
import IPython
version = IPython.__version__
if version.startswith('0.10'):
return _10shell(vars, message, prompt, exit_msg)
elif version.startswith('0.11') or \
version.startswith('0.12'):
return _12shell(vars, message, prompt, exit_msg)
else:
raise ImportError('unknown IPython version: {0}'.format(version))
except (ImportError, AttributeError):
logger.error('could not find a compatible version of IPython', exc_info=True)
## this doesn't quite work right, in that it doesn't go to the right env
## so we just fail.
import code
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
# calling this with globals ensures we can see the environment
print message
shell = code.InteractiveConsole(vars)
return shell.interact
示例8: interpreter
def interpreter(lang=None):
"""
zhpy interpreter
Accept args:
lang:
interpreter language
"""
try:
import readline
import rlcompleter
readline.parse_and_bind("tab: complete")
except ImportError:
pass
con = ZhPyConsole()
if lang == 'tw':
banner = '周蟒 %s 於 %s 基於 Python %s'%(version, sys.platform,
sys.version.split()[0])
if sys.platform == 'win32':
banner = unicode(banner, 'utf-8').encode(sys.stdout.encoding)
elif lang == 'cn':
banner = '周蟒 %s 于 %s 基于 Python %s'%(version, sys.platform,
sys.version.split()[0])
if sys.platform == 'win32':
banner = unicode(banner, 'utf-8').encode(sys.stdout.encoding)
else:
banner = 'zhpy %s in %s on top of Python %s'%(version, sys.platform,
sys.version.split()[0])
annotator()
# able to import modules in current directory
sys.path.insert(0, '')
con.interact(banner)
示例9: handle
def handle(self, options, global_options, *args):
namespace = self.make_shell_env(global_options)
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
# if options.ipython:
# try:
# import IPython
# except ImportError:
# pass
# else:
# sh = IPython.Shell.IPShellEmbed(banner=self.banner)
# sh(global_ns={}, local_ns=namespace)
# return
from code import interact, InteractiveConsole
Interpreter = MyInteractive(namespace)
if args:
def call():
execfile(args[0], namespace)
else:
call = None
Interpreter.interact(self.banner, call=call)
示例10: drop_to_shell
def drop_to_shell(local):
import rlcompleter
import readline
import code
readline.parse_and_bind("tab: complete")
code.interact(local=local)
示例11: 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: ")
示例12: 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')
示例13: 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'))
示例14: main
def main(argv):
if len(argv) <= 1:
client = SenseiClient()
else:
host = argv[1]
port = int(argv[2])
print "url specified, host: %s, port: %d" % (host,port)
client = SenseiClient(host,port,'sensei')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d - %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
def test_sql(stmt):
# test(stmt)
req = SenseiRequest(stmt)
res = client.doQuery(req)
res.display(req.get_columns(), 1000)
import readline
readline.parse_and_bind("tab: complete")
while 1:
try:
stmt = raw_input('> ')
if stmt == "exit":
break
test_sql(stmt)
except EOFError:
print
break
except ParseException as err:
print " "*err.loc + "^\n" + err.msg
示例15: 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