本文整理汇总了Python中readline.parse_and_bind函数的典型用法代码示例。如果您正苦于以下问题:Python parse_and_bind函数的具体用法?Python parse_and_bind怎么用?Python parse_and_bind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_and_bind函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:radman404,项目名称:Who-s-attacking-me-now--,代码行数:32,代码来源:wamnclient.py
示例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)
开发者ID:rory-geoghegan-ecometrica,项目名称:pudb,代码行数:30,代码来源:shell.py
示例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)
开发者ID:beyang,项目名称:cpython,代码行数:30,代码来源:site.py
示例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
开发者ID:aleasoluciones,项目名称:boscli-oss-core,代码行数:7,代码来源:boscli.py
示例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()
)
开发者ID:Jineapple,项目名称:openage,代码行数:60,代码来源:main.py
示例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)))
开发者ID:Heldroe,项目名称:fabulous,代码行数:27,代码来源:prompt.py
示例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
开发者ID:bj0,项目名称:pylans,代码行数:35,代码来源:ipshell.py
示例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)
开发者ID:BGCX261,项目名称:zhpy-svn-to-git,代码行数:33,代码来源:interpreter.py
示例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)
开发者ID:dtld,项目名称:uliweb,代码行数:27,代码来源:manage.py
示例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)
开发者ID:HalasNet,项目名称:felix,代码行数:7,代码来源:utils.py
示例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: ")
开发者ID:gera,项目名称:spg,代码行数:34,代码来源:__init__.py
示例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')
开发者ID:kheodan,项目名称:examples,代码行数:7,代码来源:examples.py
示例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'))
开发者ID:ermeaney,项目名称:nikola,代码行数:29,代码来源:console.py
示例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
开发者ID:thaingo,项目名称:sin,代码行数:35,代码来源:senseiClient.py
示例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
开发者ID:Cnlouds,项目名称:triaquae,代码行数:25,代码来源:baoleicmd.py
示例16: __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
示例17: 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
示例18: __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
示例19: main
def main(files=[]):
printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP")
printtty(colorize('> ', PROMPT_COLOR) +
"; Completion is activated using the tab (if supported by the terminal)")
for i in files:
load_relation(i)
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs')
readline.set_completer_delims(" ")
while True:
try:
line = input(colorize('> ' if TTY else '', PROMPT_COLOR))
if isinstance(line, str) and len(line) > 0:
exec_line(line)
except KeyboardInterrupt:
if TTY:
print ('^C\n')
continue
else:
break
except EOFError:
printtty()
sys.exit(0)
开发者ID:chippography,项目名称:relational,代码行数:29,代码来源:linegui.py
示例20: cmd_debug
def cmd_debug(self, argv, help):
"""Prints some debug info for this script"""
parser = argparse.ArgumentParser(
prog="aws debug",
description=help,
)
instances = self.get_instances(command='startup_script')
parser.add_argument("server", nargs=1,
metavar="instance",
help="Name of the instance from the config.",
choices=list(instances))
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", help="Print more info")
parser.add_argument("-i", "--interactive", dest="interactive",
action="store_true", help="Creates a connection and drops you into pdb")
parser.add_argument("-o", "--override", nargs="*", type=str,
dest="overrides", metavar="OVERRIDE",
help="Option to override server config for startup script (name=value).")
args = parser.parse_args(argv)
overrides = self._parse_overrides(args)
overrides['servers'] = self.instances
server = instances[args.server[0]]
startup_script = server.startup_script(overrides=overrides, debug=True)
max_size = getattr(server, 'max_startup_script_size', 16 * 1024)
log.info("Length of startup script: %s/%s", len(startup_script), max_size)
if args.verbose:
log.info("Startup script:")
print startup_script,
if args.interactive: # pragma: no cover
import readline
conn = server.conn
instance = server.instance
conn, instance # shutup pyflakes
readline.parse_and_bind('tab: complete')
__import__("code").interact(local=locals())
开发者ID:alecpm,项目名称:mr.awsome,代码行数:35,代码来源:__init__.py
注:本文中的readline.parse_and_bind函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论