def interactive(self):
utils.set_prompt(ps1="(rudra) ", ps2="... ")
import os
import readline
import rlcompleter
import atexit
histfile = os.path.join(os.environ["HOME"], ".rudrahistory")
if os.path.isfile(histfile):
readline.read_history_file(histfile)
atexit.register(readline.write_history_file, histfile)
r = self
print "Use the \"r\" object to analyze files"
vars = globals()
vars.update(locals())
readline.set_completer(rlcompleter.Completer(vars).complete)
readline.parse_and_bind("tab: complete")
del os, histfile, readline, rlcompleter, atexit
code.interact(banner="", local=vars)
python类parse_and_bind()的实例源码
def log_exercise(settings, logs, start_log):
completer = MyCompleter([str(k) for k in workouts])
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
while True:
# because windows has to be special
if sys.platform.startswith('win'):
choose_extra = "(Tab for options)"
else:
choose_extra = "(Double tab for options)"
choose_ = input('What workout did you do? {0}: '.format(choose_extra))
if choose_.capitalize() not in workouts.keys():
pass
else:
if choose_.capitalize() == 'Cardio':
cardio.main(settings, logs)
elif choose_.capitalize() == 'Log':
print("Not yet done")
elif choose_.capitalize() == 'Settings':
settings_change(settings)
else:
physical.main(choose_, settings)
body_checks(settings, start_log)
def setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
if not os.path.exists(self.history_file):
open(self.history_file, 'a+').close()
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;')
readline.parse_and_bind("tab: complete")
def setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
if not os.path.exists(self.history_file):
open(self.history_file, 'a+').close()
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;')
readline.parse_and_bind("tab: complete")
def run(self, args):
try:
if not self.client.conn.modules["os.path"].exists("C:\\WIndows\\system32\\Packet.dll"):
raise PupyModuleError("WinPcap is not installed !. You should download/upload NPcap (https://github.com/nmap/npcap/releases) and install it silently (with the /S flag) ")
if not self.client.conn.modules['ctypes'].windll.Shell32.IsUserAnAdmin():
self.warning("you are running this module without beeing admin")
with redirected_stdo(self.client.conn):
old_completer=readline.get_completer()
try:
psc=self.client.conn.modules['pyshell.controller'].PyShellController()
readline.set_completer(psc.get_completer())
readline.parse_and_bind('tab: complete')
psc.write("from scapy.all import *")
while True:
cmd=raw_input(">>> ")
psc.write(cmd)
finally:
readline.set_completer(old_completer)
readline.parse_and_bind('tab: complete')
except KeyboardInterrupt:
pass
def run(self, args):
try:
with redirected_stdo(self.client.conn):
old_completer=readline.get_completer()
try:
psc=self.client.conn.modules['pyshell.controller'].PyShellController()
readline.set_completer(psc.get_completer())
readline.parse_and_bind('tab: complete')
while True:
cmd=raw_input(">>> ")
psc.write(cmd)
finally:
readline.set_completer(old_completer)
readline.parse_and_bind('tab: complete')
except KeyboardInterrupt:
pass
def do_python(self,arg):
""" start the local python interpreter (for debugging purposes) """
orig_exit=builtins.exit
orig_quit=builtins.quit
def disabled_exit(*args, **kwargs):
self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
builtins.exit=disabled_exit
builtins.quit=disabled_exit
oldcompleter=readline.get_completer()
try:
local_ns={"pupsrv":self.pupsrv}
readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
readline.parse_and_bind('tab: complete')
code.interact(local=local_ns)
except Exception as e:
self.display_error(str(e))
finally:
readline.set_completer(oldcompleter)
readline.parse_and_bind('tab: complete')
builtins.exit=orig_exit
builtins.quit=orig_quit
def enable_autocomplete_and_history(adir, env):
try:
import rlcompleter
import atexit
import readline
except ImportError:
pass
else:
readline.parse_and_bind("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 run(self, args):
try:
if not self.client.conn.modules["os.path"].exists("C:\\WIndows\\system32\\Packet.dll"):
raise PupyModuleError("WinPcap is not installed !. You should download/upload NPcap (https://github.com/nmap/npcap/releases) and install it silently (with the /S flag) ")
if not self.client.conn.modules['ctypes'].windll.Shell32.IsUserAnAdmin():
self.warning("you are running this module without beeing admin")
with redirected_stdo(self.client.conn):
old_completer=readline.get_completer()
try:
psc=self.client.conn.modules['pyshell.controller'].PyShellController()
readline.set_completer(psc.get_completer())
readline.parse_and_bind('tab: complete')
psc.write("from scapy.all import *")
while True:
cmd=raw_input(">>> ")
psc.write(cmd)
finally:
readline.set_completer(old_completer)
readline.parse_and_bind('tab: complete')
except KeyboardInterrupt:
pass
def run(self, args):
try:
with redirected_stdo(self.client.conn):
old_completer=readline.get_completer()
try:
psc=self.client.conn.modules['pyshell.controller'].PyShellController()
readline.set_completer(psc.get_completer())
readline.parse_and_bind('tab: complete')
while True:
cmd=raw_input(">>> ")
psc.write(cmd)
finally:
readline.set_completer(old_completer)
readline.parse_and_bind('tab: complete')
except KeyboardInterrupt:
pass
def do_python(self,arg):
""" start the local python interpreter (for debugging purposes) """
orig_exit=builtins.exit
orig_quit=builtins.quit
def disabled_exit(*args, **kwargs):
self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
builtins.exit=disabled_exit
builtins.quit=disabled_exit
oldcompleter=readline.get_completer()
try:
local_ns={"pupsrv":self.pupsrv}
readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
readline.parse_and_bind('tab: complete')
code.interact(local=local_ns)
except Exception as e:
self.display_error(str(e))
finally:
readline.set_completer(oldcompleter)
readline.parse_and_bind('tab: complete')
builtins.exit=orig_exit
builtins.quit=orig_quit
def __init__(self):
try:
self.read_config()
except:
c = {}
c['url'] = raw_input(u"Enter server hostname or IP address: ")
c['username'] = raw_input(u"Enter user name: ")
c['password'] = getpass(u"Enter password: ")
self.config['credentials'] = c
self.pve = Pveconn(**self.config['credentials'])
if '-c' in sys.argv:
command = sys.argv[sys.argv.index('-c')+1:]
self.parse_command(command)
else:
readline.parse_and_bind("tab: complete")
readline.set_completer(self.complete)
self.wait()
def enable_autocomplete_and_history(adir, env):
try:
import rlcompleter
import atexit
import readline
except ImportError:
pass
else:
readline.parse_and_bind("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 get_query(prompt):
"""
Get input from a user terminated by a semicolon and return a string.
:param prompt: A prompt string.
:type prompt: str
:return: User input without a trailing semicolon.
:rtype: str
"""
readline.parse_and_bind('set editing-mode vi')
query = ""
while True:
line = raw_input(prompt)
query += "%s " % line
if ';' in line:
break
user_input = query.split(';', 1)[0]
user_input = user_input.strip(' \n\t')
return user_input
def setup(histfn=None, button='tab',verbose=1):
if histfn is None:
base = os.getenv('HOME')
if not base:
import tempfile
base = tempfile.gettempdir()
histfn = os.path.join(base, '.pythonhist')
import readline
completer = Completer()
readline.set_completer_delims('')
readline.set_completer(completer.rl_complete)
readline.parse_and_bind(button+': complete')
if histfn:
setup_readline_history(histfn)
if verbose:
print ("Welcome to rlcompleter2 %s" % __version__)
print ("for nice experiences hit <%s> multiple times"%(button))
def hook_readline_hist():
try:
import readline
except ImportError:
return
histfile = os.environ['HOME'] + '/.web_develop_history' # ???????????????
readline.parse_and_bind('tab: complete')
try:
readline.read_history_file(histfile)
except IOError:
pass # It doesn't exist yet.
def savehist():
try:
readline.write_history_file(histfile)
except:
print 'Unable to save Python command history'
atexit.register(savehist)
def run(self):
"""Run the command interpreter."""
readline.parse_and_bind('')
while True:
line = input('>>> ').strip()
# Redirect output to a file:
try:
separator_index = line.index('>')
command = line[:separator_index]
redirect_file = line[separator_index + 1:].strip()
# Output to stdout:
except ValueError:
command = line
redirect_file = None
command = [x.strip() for x in command.split()]
if redirect_file:
with open(redirect_file, 'w') as f:
with redirect_stdout(f):
self._dispatch_command(command[0], command[1:])
else:
self._dispatch_command(command[0], command[1:])
def run(self, line):
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
sample_file = raw_input('Please enter the filename you want to open: ')
try:
sample_fh = open(sample_file,'r')
feathermodules.samples.extend([sample.strip() for sample in sample_fh.readlines()])
sample_fh.close()
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
except:
print 'Something went wrong. Sorry! Please try again.'
finally:
readline.set_completer(ishellCompleter)
def run(self, line):
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
sample_file = raw_input('Please enter the filename you want to open: ')
try:
sample_fh = open(sample_file,'r')
feathermodules.samples.append(sample_fh.read())
sample_fh.close()
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
except:
print 'Something went wrong. Sorry! Please try again.'
finally:
readline.set_completer(ishellCompleter)
def enable_autocomplete_and_history(adir, env):
try:
import rlcompleter
import atexit
import readline
except ImportError:
pass
else:
readline.parse_and_bind("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 ask_list(label, items, alt=None, default=None):
completer = AutoCompleter(items)
readline.set_completer(completer.complete)
readline.set_completer_delims('')
readline.parse_and_bind('tab: complete')
item = None
while not item:
item = ask_string(label, default=default)
if item not in items:
if alt and item in alt:
item = items[alt.index(item)]
else:
print("Invalid entry (try pressing TAB)")
item = None
readline.set_completer(None)
return item
def get_command(self, prompt, auto_complete_fn=None):
try:
if auto_complete_fn != None:
import readline
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(auto_complete_fn)
except:
pass
# python3 changes raw input name
if sys.version_info[0] == 3:
raw_input = input
else:
raw_input = __builtins__['raw_input']
cmd = raw_input("%s" % prompt)
return cmd.strip()
def pre_input(self, completefn):
if self.raw_input:
if HAVE_READLINE:
import atexit
self.old_completer = readline.get_completer()
# Fix Bug #3129: Limit the history size to consume less memory
readline.set_history_length(self.historysize)
readline.set_completer(completefn)
readline.parse_and_bind(self.completekey+": complete")
try:
readline.read_history_file()
except IOError:
pass
atexit.register(readline.write_history_file)
self.havecolor = True
if mswindows and self.enablecolor:
self.cwrite = readline.GetOutputFile().write_color
else:
self.cwrite = self.stdout.write
def enable_autocomplete_and_history(adir, env):
try:
import rlcompleter
import atexit
import readline
except ImportError:
pass
else:
readline.parse_and_bind("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 enable_autocomplete_and_history(adir, env):
try:
import rlcompleter
import atexit
import readline
except ImportError:
pass
else:
readline.parse_and_bind("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_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 setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
if not os.path.exists(self.history_file):
open(self.history_file, 'a+').close()
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;')
readline.parse_and_bind("tab: complete")
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 setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
if not os.path.exists(self.history_file):
open(self.history_file, 'a+').close()
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;')
readline.parse_and_bind("tab: complete")
def pre_input(self, completefn):
if self.raw_input:
if HAVE_READLINE:
import atexit
self.old_completer = readline.get_completer()
# Fix Bug #3129: Limit the history size to consume less memory
readline.set_history_length(self.historysize)
readline.set_completer(completefn)
readline.parse_and_bind(self.completekey+": complete")
try:
readline.read_history_file()
except IOError:
pass
atexit.register(readline.write_history_file)
self.havecolor = True
if mswindows and self.enablecolor:
self.cwrite = readline.GetOutputFile().write_color
else:
self.cwrite = self.stdout.write