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类set_completer()的实例源码
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 __exit__(self, ex_tp, ex_val, ex_tb):
if not haveReadline:
return False
try:
# update the history for this project
readline.write_history_file(self.historyFile)
except Exception as E:
print "Failed to write history to {0} - {1}".format(self.historyFile, E)
# put back the original history!
readline.clear_history()
readline.read_history_file(self.oldhistFile)
os.unlink(self.oldhistFile)
# and put back the old completer
readline.set_completer(self.oldCompleter)
# linegenerators, pass one of these to the "run"
# method of the CommandLineInterface object
#import ctypes
#rllib = ctypes.cdll.LoadLibrary("libreadline.so")
#rl_line_buffer = ctypes.c_char_p.in_dll(rllib, "rl_line_buffer")
#rl_done = ctypes.c_int.in_dll(rllib, "rl_done")
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 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 config():
show()
choose = raw_input('???????ip????????all:')
try:
if 'all' == choose:
ip_list = SLAVE_LIST
else:
ip_list = [SLAVE_LIST[int(i)] for i in choose.split()]
readline.set_completer(path_completer)
_path = raw_input('??????????:')
for ip in ip_list:
print 'IP: ', ip, 'is proccessing...'
address = "http://{}:12001/".format(ip)
proxy = xmlrpclib.ServerProxy(address)
with open(_path, 'r') as f:
print 'Result:', str(proxy.config(f.read()))
proxy('close')
except:
print traceback.format_exc()
print 'Done.'
def upload_script():
show()
choose = raw_input('???????ip????????all:')
try:
if 'all' == choose:
ip_list = SLAVE_LIST
else:
ip_list = [SLAVE_LIST[int(i)] for i in choose.split()]
readline.set_completer(path_completer)
_path = raw_input('??????????:')
for ip in ip_list:
print 'IP: ', ip, 'is proccessing...'
address = "http://{}:12001/".format(ip)
proxy = xmlrpclib.ServerProxy(address)
with open(_path, 'r') as f:
print 'Result:', str(proxy.upload_script(os.path.basename(_path), f.read()))
proxy('close')
except:
print traceback.format_exc()
print 'Done.'
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