def __init__(self,eerpom): Cmd.__init__(self) self.eerpom = eerpom self.table = eerpom self.stop = False self.prompt = STR_PROMPT
def __init__(self, conf_file, custom_api=None, custom_print=None, custom_repr_as_table=None): Cmd.__init__(self) here = os.path.abspath(os.path.dirname(conf_file)) self.config = ConfigParser(defaults={'here': here}) self.config.read(conf_file) db_string = self.config.get('app:lasco', 'lasco.db_string') self.engine = create_engine(db_string) self.session = sessionmaker(self.engine)() # The following customizations are here for our tests. if custom_api: self.api = custom_api else: self.api = ExceptionWrapper(lasco.api) if custom_print: self.print_ = custom_print else: # pragma: no coverage self.print_ = lambda msg: sys.stdout.write( msg.encode(DEFAULT_ENCODING) + os.linesep) if custom_repr_as_table: self.repr_as_table = custom_repr_as_table else: # pragma: no coverage self.repr_as_table = repr_as_table
def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout): Cmd.__init__(self, 'Tab', stdin, stdout) ConnectionListener.__init__(self) self.prompt = prompt self.verbose = verbose self.user = user self.passcode = passcode self.__quit = False if ver == '1.0': self.conn = StompConnection10([(host, port)], wait_on_receipt=True) elif ver == '1.1': self.conn = StompConnection11([(host, port)], wait_on_receipt=True) elif ver == '1.2': self.conn = StompConnection12([(host, port)], wait_on_receipt=True) elif ver == 'multicast': self.conn = MulticastConnection() else: raise RuntimeError('Unknown version') if use_ssl: self.conn.set_ssl([(host, port)]) self.conn.set_listener('', self) self.conn.start() self.conn.connect(self.user, self.passcode, wait=True) self.transaction_id = None self.version = ver try: self.nversion = float(ver) except ValueError: self.nversion = 1.0 self.__subscriptions = {} self.__subscription_id = 1
def __init__(self, stdin=sys.stdin, foreground=True): self.bridge = None # default bridge self.ipt = None self.nss = None self.dvr = None if foreground: self.prompt = color_str(PROMPT_KW, 'g') self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output("***\n Welcome to EasyOVS %s, " "type help to see available cmds.\n***\n" % VERSION) info('*** Starting CLI:\n') debug("==Loading credentials==\n") debug("auth_url = %s\n" % os.getenv('OS_AUTH_URL') or cfg.CONF.OS.auth_url) debug("username = %s\n" % os.getenv('OS_USERNAME') or cfg.CONF.OS.username) passwd = os.getenv('OS_PASSWORD') or cfg.CONF.OS.password passwd = passwd[:len(passwd)/4] + "****" + passwd[-len(passwd)/4:] debug("password = %s\n" % passwd) debug("tenant_name = %s\n" % os.getenv('OS_TENANT_NAME') or cfg.CONF.OS.tenant_name) while True: try: #if self.isatty(): #quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info('\nInterrupt\n')
def __init__(self): Cmd.__init__(self) # Constants self.prompt = 'rr_dbg>' self.qemu_replay_keyword = '-replay' self.gdb_connect_cmd = 'target remote localhost:1234' self.setup_time = 8 # Regexes # '=> 0xc000c000:\tmov\t%eax,0x20(%ebx)\n' self.ins_line_regex = re.compile('.*0x(.*):\s*([a-z]+)\s*(.*)\s*') # read from init file self.vmlinux = 'vmlinux' self.vmlinux_strip_prefix = '' self.gdb_exec = '/usr/bin/gdb' self.qemu_exec = 'qemu' self.qemu_args = ['-s', '-no-reboot'] self.qemu_replay_file = 'r.log' self.gdb_macros = None self.executable = None self.qemu_cwd = None self.image = None # Processes, dynamic data, flags self.qemu_process = None self.gdb_pexpect = None self.executable_start_dump = None self.gdb_running = False # DB stuff self.db_file_name = 'rrdebug.sqlite' self.conn = None self.cursor = None
def __init__(self, admin_cli): # remove stdout stream encoding while in 'shell' mode, becuase this breaks readline # (autocompletion and shell history). In 'shell' mode the stdout # is encoded just for time necessary for command execution see precmd a postcmd sys.stdout = stdout_origin self.stdout_with_codec = encode_stream(sys.stdout, "utf-8") self.completion_matches = None Cmd.__init__(self) self.admin_cli = admin_cli self.completion = Completion(self.admin_cli) try: Config() self.prompt = Config.parser.get('shell', 'prompt') + ' ' except (ConfigFileError, ConfigParser.Error): self.prompt = 'katello> ' try: # don't split on hyphens during tab completion (important for completing parameters) newdelims = readline.get_completer_delims() newdelims = re.sub('-', '', newdelims) readline.set_completer_delims(newdelims) if (Config.parser.get('shell', 'nohistory').lower() != 'true'): self.__init_history() except ConfigParser.Error: pass self.__init_commands()
def __init__(self, site_config=None): Cmd.__init__(self) self.__site_config = site_config shell_context = ShellContext(self) self.__shell_context = shell_context self.__history_file = os.path.join(os.path.expanduser("~/.ertshell/ertshell.history")) self.__init_history() matplotlib.rcParams["backend"] = "Qt4Agg" matplotlib.rcParams["interactive"] = True matplotlib.rcParams["mathtext.default"] = "regular" matplotlib.rcParams["verbose.level"] = "helpful" matplotlib.rcParams["verbose.fileo"] = "sys.stderr" try: matplotlib.style.use("ggplot") # available from version 1.4 except AttributeError: pass Debug(shell_context) PlotSettings(shell_context) Workflows(shell_context) Cases(shell_context) Plugins(shell_context) SummaryKeys(shell_context) GenDataKeys(shell_context) GenKWKeys(shell_context) Results(shell_context)
def __init__(self): Cmd.__init__(self) self.prompt = "\x1b[1;34m%s\x1b[0m> " % "torrent-sentinel" self.emptyline = lambda : 0 self.ruler = '' self.complete_info = self.complete_search self.complete_download = self.complete_search
def __init__(self,casename,bench, sutnames , logfiledir, outputfile =None): if outputfile: pass else: outputfile=sys.stdout self.benchinfo = bench2dict(bench) #self.benchinfo = benchinfo self.casename =casename self.sut ={} for sutname in sutnames: self.sut.update({sutname:self.benchinfo[sutname]}) steps=[[],[],[]] mode ='FULL' self.tc= Case(casename,self.sut,steps=[[],[],[]],mode='FULL',DebugWhenFailed=False,logdir=logfiledir,caseconfigfile='../lib/case.cfg') self.thQureyOut = threading.Thread(target=self.QureyOutput,args = [] )#outputfile self.thQureyOut.start() self.client ='interaction' self.tc.AddClient(self.client) self.tc.troubleshooting() nowTime =time.time() self.lastCmdIssueTime=nowTime Cmd.__init__(self, 'tab', sys.stdin, sys.stdout) self.use_rawinput=True #import readline #readline.set_completer_delims('\t\n') # def do_set(self,name): # print(name) self.do_setsut(self.tc.Session.keys()[-1]) self.helpDoc={} self.cmdbank=[]
def __init__(self, vlab, stdin=sys.stdin): """Instantiates a CLI object :param vlab: Vlab class to be run""" self.stdin = stdin self.vlab = vlab Cmd.__init__(self) print('Starting CLI:\n') # Setup history if readline is available try: import readline except ImportError: pass else: history_path = os.path.expanduser('~/.vlab_history') if os.path.isfile(history_path): readline.read_history_file(history_path) atexit.register( lambda: readline.write_history_file(history_path)) while True: try: if self.isatty(): run('stty sane') self.cmdloop() break except KeyboardInterrupt: print('\nInterrupt\n')
def __init__(self, memobj, config=None, symobj=None): self.extcmds = {} self.basecmds = [] self.emptymeth = None self.extsubsys = collections.defaultdict(list) self.scriptpaths = [] self.addScriptPathEnvVar('ENVI_SCRIPT_PATH') Cmd.__init__(self, stdout=self) for name in dir(self): if name.startswith('do_'): self.basecmds.append(name[3:]) self.shutdown = threading.Event() # If they didn't give us a resolver, make one. if symobj is None: symobj = e_resolv.SymbolResolver() if config is None: config = e_config.EnviConfig(defaults=cfgdefs) # Force it to be there if its not config.getSubConfig('cli') self.config = config self.memobj = memobj self.symobj = symobj self.canvas = e_canvas.MemoryCanvas(memobj, syms=symobj) self.aliases = {} # For *runtime* aliases only!
def __init__(self, subruler='-', completekey='tab', stdin=None, stdout=None): Cmd.__init__(self, completekey, stdin, stdout) self.subruler = subruler self.prompt = '>>> ' self.stack = Stack() self.string_mode = False self.pc = '>'
def __init__(self, admin_url=None): Cmd.__init__(self) self.admin_url = None self.admin_proxy = None if admin_url is not None: self.do_connect(admin_url)
def __init__(self, framework, plugins_path): Cmd.__init__(self) self._framework = framework self._plugins_path = os.path.abspath(plugins_path) sys.path.append(self._plugins_path) self._config = configparser.ConfigParser() config_fn = os.path.join(self._plugins_path, 'config.ini') if os.path.exists(config_fn): self._config.read(config_fn) for section in self._config.sections(): try: _f = self._framework.install_bundle(section) if self._config.get(section, 'start'): _f.result().start().result() except configparser.NoOptionError: pass except BaseException as e: print(' bundle {0} init error:'.format(section), e) self._config.remove_section(section) self.intro = 'Gumpy runtime console' self.prompt = '>>> '
def __init__(self, corpus, dictionary, model, possible_matches=None): Cmd.__init__(self) self.prompt = "> " self.corpus = corpus self.dictionary = dictionary self.model = model self.possible_matches = possible_matches
def __init__(self, image, completekey='tab', stdin=None, stdout=None): Cmd.__init__(self, completekey=completekey, stdin=stdin, stdout=stdout) self.curdir = "/" self.rdisk = None if image.filename == "remote": self.rdisk = RamdiskToolClient.get() self.device_infos = image.device_infos self.complete_open = self._complete self.complete_xattr = self._complete self.complete_cprotect = self._complete self.complete_ls = self._complete self.complete_cd = self._complete self.complete_plist = self._complete self.complete_xxd = self._complete self.image = image if image.ppn and image.filename == "remote": self.savepath = "." print "Remote PPN device, use nand_dump + save, other commands will fail" return self.system = image.getPartitionVolume(0) self.data = image.getPartitionVolume(1) self.volume = None self.volname = "" grab_system_version(self.system, self.device_infos) print "Keybag state: %slocked" % (int(self.data.keybag.unlocked) * "un") self.deviceName = get_device_name(self.data) self.do_data("") self.savepath = os.path.join(os.path.dirname(image.filename), "%s.plist" % self.device_infos.udid[:10]) #if image.iosVersion > 3 and not image.device_infos.has_key("passcode"): # print "No passcode found in plist file, bruteforce required to access protected data" self.carver = None
def __init__(self, completekey='tab', stdin=None, stdout=None): self.client = FicloudDeployment() self.client.init(os.getcwd(), 'dev') self.update_prompt() Cmd.__init__(self, completekey, stdin, stdout)
def __init__( self, mininet, stdin=sys.stdin, script=None ): self.mn = mininet # Local variable bindings for py command self.locals = { 'net': mininet } # Attempt to handle input self.stdin = stdin self.inPoller = poll() self.inPoller.register( stdin ) self.inputFile = script Cmd.__init__( self ) info( '*** Starting CLI:\n' ) if self.inputFile: self.do_source( self.inputFile ) return while True: try: # Make sure no nodes are still waiting for node in self.mn.values(): while node.waiting: node.sendInt() node.monitor() if self.isatty(): quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: output( '\nInterrupt\n' )
def __init__(self, options, args=None, rcfid=None): Cmd.__init__(self) self.options = options self.read_allowed_list = [] self.ramwrite_allowed_list = [] self.flashwrite_allowed_list = [] self.exec_allowed_list = [] self.nointeractive = options.nointeractive self.startaddress = -1 if rcfid is not None: self.source(rcfid) if args is not None: enquote(args) # Multiple commands can be split using commas while 1: try: ix = args.index(',') except ValueError: break self.cmdqueue.append(string.join(args[:ix], ' ')) args = args[ix+1:] if len(args): self.cmdqueue.append(string.join(args, ' '))
def __init__(self, completekey='tab', stdin=None, stdout=None): Cmd.__init__(self, completekey, stdin, stdout) # base wafterpreter constants self.intro = "Welcome to Bywaf" self.base_prompt = "Bywaf" self.set_prompt('') # set the prompt self.delegate_input_handler = None # no delegated input by default # currently loaded plugins, loaded & selected with he "use" command. # is a dictionary of { "plugin_name" : loaded_module_object } self.plugins = {} # dictionary of global variable names and values self.global_options = {} # jobs are spawned using this object's "submit()" # self.job_executor = concurrent.futures.ProcessPoolExecutor(DEFAULT_MAX_CONCURRENT_JOBS) self.job_executor = concurrent.futures.ThreadPoolExecutor(DEFAULT_MAX_CONCURRENT_JOBS) # running counter, increments with every job; used as Job ID self.job_counter = 0 # job pool (list of runnign and completed Futures objects) self.jobs = [] # currently-selected plugin's name and object (reference to a job in self.jobs) self.current_plugin = None self.current_plugin_name = '' # list of newly-finished backgrounded plugin command jobs self.finished_jobs = []
def __init__(self): self.prompt = '> ' Cmd.__init__(self) self.circuit = Circuit() self.display = print self.cmdloop('')
def __init__(self, settings): Cmd.__init__(self) self.SETTINGS = settings self.commands = [] for s in dir(self): if re.match(r'do_',s): self.commands.append(re.sub(r'do_','',s))
def __init__(self): Cmd.__init__(self) self.prompt = '(Subdomainator) > ' self.do_help.__func__.__doc__ = '''Displays the help menu.''' self.doc_header = 'Commands' self.menu_state = "main"
def __init__(self): """Initialize a MyCmd object. Searches for any methods named sub_* and adds the do_* and list_* methods """ Cmd.__init__(self) names = dir(self.__class__) for name in names: if name[:4] == 'sub_': sub = getattr(self, name)() subname = name[4:] setattr(self, subname, sub) def make_sub(asub, doc): def do_sub(self, args): asub.onecmd(args) do_sub.__doc__ = doc return do_sub setattr(self.__class__, "do_" + subname, make_sub(sub, getattr(self, name).__doc__)) if "list_" + subname not in names: def make_list(asub, aname): def do_list(self, args): asub.do_list(args + aname + " ") return do_list setattr(self.__class__, "list_" + subname, make_list(sub, subname))
def __init__( self, mininet, stdin=sys.stdin, script=None ): self.mn = mininet self.nodelist = self.mn.controllers + self.mn.switches + self.mn.hosts self.nodemap = {} # map names to Node objects for node in self.nodelist: self.nodemap[ node.name ] = node # Attempt to handle input self.stdin = stdin self.inPoller = poll() self.inPoller.register( stdin ) self.inputFile = script Cmd.__init__( self ) info( '*** Starting CLI:\n' ) if self.inputFile: self.do_source( self.inputFile ) return while True: try: # Make sure no nodes are still waiting for node in self.nodelist: while node.waiting: node.sendInt() node.monitor() if self.isatty(): quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: output( '\nInterrupt\n' )
def __init__(self, ctrl): Cmd.__init__(self) self._ctrl = ctrl self._changeset = ChangeSet(ctrl.getCache()) self._undo = [] self._redo = []
def __init__( self, mininet, stdin=sys.stdin, script=None ): """Start and run interactive or batch mode CLI mininet: Mininet network object stdin: standard input for CLI script: script to run in batch mode""" self.mn = mininet # Local variable bindings for py command self.locals = { 'net': mininet } # Attempt to handle input self.stdin = stdin self.inPoller = poll() self.inPoller.register( stdin ) self.inputFile = script Cmd.__init__( self ) info( '*** Starting CLI:\n' ) if self.inputFile: self.do_source( self.inputFile ) return self.initReadline() self.run()
def __init__(self, savedata): Cmd.__init__(self) self._save_manager = SaveManager(savedata.savefile, savedata.gluid) data, self.save_number = self._save_manager.load(savedata.legacy) if not savedata.legacy: data = decompress_data(data) self._xml_handle = XmlHandler(data) self._xml_handle.pre_load() self.savedata = savedata self._show_functions = { 'currencies': show_currencies, 'currency': show_currency, 'ponies': show_ponies, 'pony': show_pony, 'zones': show_zones, 'zone': show_zone, } self._set_functions = { 'currency': set_currency, 'ponies': set_ponies, 'pony': set_pony, 'zones': set_zones, 'zone': set_zone, 'inventory': set_inventory, }
def __init__(self,world = None,game_out_q=None, stdin=sys.stdin, parent=None): Cmd.__init__(self) self.use_rawinput = False self.parent = parent self.game_out_q = game_out_q self.exit = False print(str(__name__) + ' using input %s' % self.stdin)
def __init__(self, client): if issubclass(Cmd, object): super().__init__() else: Cmd.__init__(self) self.client = client
def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, heartbeats=(0, 0), stdin=sys.stdin, stdout=sys.stdout): Cmd.__init__(self, 'Tab', stdin, stdout) ConnectionListener.__init__(self) self.prompt = prompt self.verbose = verbose self.user = user self.passcode = passcode self.__quit = False if ver == '1.0': self.conn = StompConnection10([(host, port)], wait_on_receipt=True) elif ver == '1.1': self.conn = StompConnection11([(host, port)], wait_on_receipt=True, heartbeats=heartbeats) elif ver == '1.2': self.conn = StompConnection12([(host, port)], wait_on_receipt=True, heartbeats=heartbeats) elif ver == 'multicast': self.conn = MulticastConnection() else: raise RuntimeError('Unknown version') if use_ssl: self.conn.set_ssl([(host, port)]) self.conn.set_listener('', self) self.conn.start() self.conn.connect(self.user, self.passcode, wait=True) self.transaction_id = None self.version = ver try: self.nversion = float(ver) except ValueError: self.nversion = 1.0 self.__subscriptions = {} self.__subscription_id = 1
def __init__(self, dir=os.getcwd()): Cmd.__init__(self, dir) self.dir = dir self.prompt = ">>" + dir + ">> " self.hosts = [] self.connections = [] self.con = Converter() self.loop = asyncio.get_event_loop() self.intro = "This program will generate a class diagram from your JavaScript source code. " \ "Type help for a list of commands." jloader = JsonLoader('help_file.json') # self.do_load_data("JSTest2.js") # test try: jloader.open_file() except FileNotFoundError: print('There is no help file.') self.jloader = jloader
def __init__(self, url, dirname, urlfile): Cmd.__init__(self) self.secret = randomString(SECRET_LENGTH) n = Node(url, dirname, self.secret) t = Thread(target = n._start) t.setDaemon(1) t.start() sleep(HEAD_START) self.server = ServerProxy(url) self.dirname=dirname self.urlfile=urlfile print "=============================",dirname+"/"+urlfile for line in open(dirname+"/"+urlfile): line = line.strip() self.server.hello(line)
def __init__(self, url, dirname, urlfile): """ URL, ディレクトリ名、URLファイルを設定し、 ノードサーバーを別スレッドで起動する """ Cmd.__init__(self) self.secret = random_string(SECRET_LENGTH) n = Node(url, dirname, self.secret) t = Thread(target=n._start) t.setDaemon(1) t.start() # サーバーに起動をかける sleep(HEAD_START) self.server = ServerProxy(url) for line in open(urlfile): line = line.strip() self.server.hello(line)
def __init__(self): self.net = N_Request() self.config = config() self.db = DB() self.output = CLIOutput() self.output2 = O_Output() self.exp = exp() Cmd.__init__(self) os.system("clear") self.output.printYellow( self.config.logo + "Welcome To Auto-Exploit-Framework\nThe world Will Remember You Forever" ) self.case_insensitive = False self.prompt = self.config.default_console_words self.isused = False self.file = IO_File()
def __init__(self, afcname='com.apple.afc', completekey='tab', stdin=None, stdout=None, client=None, udid=None, logger=None): Cmd.__init__(self, completekey=completekey, stdin=stdin, stdout=stdout) self.logger = logger or logging.getLogger(__name__) self.lockdown = LockdownClient() self.afc = client if client else AFCClient( self.lockdown, serviceName=afcname, udid=udid) self.curdir = '/' self.prompt = 'AFC$ ' + self.curdir + ' ' self.complete_cat = self._complete self.complete_ls = self._complete
def __init__(self, app, websrv): ''' :param app: OpenVisualizerApp :param websrv: Web server ''' log.info('Creating OpenVisualizerWeb') # store params self.app = app self.engine = SimEngine.SimEngine() self.websrv = websrv # command support Cmd.__init__(self) self.doc_header = 'Commands (type "help all" or "help <topic>"):' self.prompt = '> ' self.intro = '\nOpenVisualizer (type "help" for commands)' #used for remote motes : self.roverMotes = {} self.client = coap.coap(udpPort=9000) self.client.respTimeout = 2 self.client.ackTimeout = 2 self.client.maxRetransmit = 1 self._defineRoutes() # To find page templates bottle.TEMPLATE_PATH.append('{0}/web_files/templates/'.format( self.app.datadir)) # initialize parent class eventBusClient.eventBusClient.__init__( self, name='OpenVisualizerWeb', registrations=[], ) # Set DAGroots imported if app.DAGrootList: #Wait the end of the mote threads creation time.sleep(1) for moteid in app.DAGrootList: self._showMoteview(moteid) self._getMoteData(moteid) self._toggleDAGroot(moteid)
def __init__(self): Cmd.__init__(self) self.prompt = 'MGPro>' self.aliases = { 'c': self.do_continuation, 'g': self.do_gradient, 'p': self.do_plot, 'q': self.do_quit, 'r': self.do_read, 's': self.do_powspec, 'w': self.do_write, 'x': self.do_dt2xa, 'y': self.do_dt2ya, 'z': self.do_dt2za, 'h': self.do_help } self.result = None
def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self.speech = create_voice() self.actions = [{"check": ("ram", "weather", "time", "forecast")}, "directions", "help", "how_are_you", "near", "pinpoint", "umbrella", {"update": ("location", "system")}, "weather", ] self.fixed_responses = {"what time is it": "clock", "where am i": "pinpoint", "how are you": "how_are_you" } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() count_disabled_plugins = len(self._plugin_manager.get_disabled()) if count_disabled_plugins > 0: self.first_reaction_text += Fore.RED + str(count_disabled_plugins) + Fore.BLUE self.first_reaction_text += " plugins are disabled. For more information, type: " self.first_reaction_text += Fore.RED + 'status\n' + Fore.RESET
def __init__(self, mininet, stdin=sys.stdin, script=None): """Start and run interactive or batch mode CLI mininet: Mininet network object stdin: standard input for CLI script: script to run in batch mode""" if mobility.isMobility == False and mobility.DRAW: for sta in mininet.stations: if 'position' not in sta.params: sta.params['position'] = 0, 0, 0 if mobility.accessPoints == []: mobility.accessPoints = mininet.accessPoints if mobility.stations == []: mobility.stations = mininet.stations nodes = mininet.stations + mininet.accessPoints + mininet.plotNodes if mininet.is3d: plot3d.instantiateGraph(mininet.MAX_X, mininet.MAX_Y, mininet.MAX_Z) plot3d.graphInstantiateNodes(nodes) else: plot2d.instantiateGraph(mininet.MAX_X, mininet.MAX_Y) plot2d.plotGraph(nodes, mininet.srcConn, mininet.dstConn, mininet.MAX_X, mininet.MAX_Y) plot2d.graphPause() self.mn = mininet # Local variable bindings for py command self.locals = {'net': mininet} # Attempt to handle input self.stdin = stdin self.inPoller = poll() self.inPoller.register(stdin) self.inputFile = script Cmd.__init__(self) info('*** Starting CLI:\n') if self.inputFile: self.do_source(self.inputFile) return self.initReadline() self.run()
def __init__(self, url, dirname, urlfile): """ Sets the url, dirname, and urlfile, and starts the Node Server in a separate thread. """ Cmd.__init__(self) self.secret = randomString(SECRET_LENGTH) n = Node(url, dirname, self.secret) t = Thread(target=n._start) t.setDaemon(1) t.start() # Give the server a head start: sleep(HEAD_START) self.server = ServerProxy(url) for line in open(urlfile): line = line.strip() self.server.hello(line)
def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self._api = JarvisAPI(self) # Remember voice settings self.enable_voice = self._api.get_data('enable_voice') self.speech_rate = self._api.get_data('speech_rate') if not self.speech_rate: self.speech_rate = 120 # what if the platform does not have any engines, travis doesn't have sapi5 acc to me try: self.speech = create_voice(rate=self.speech_rate) except Exception as e: print_say("Voice not supported", self, Fore.RED) print_say(str(e), self, Fore.RED) self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", } self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() self._init_plugin_info()
def __init__(self, options, conf_dir, config_parser): Cmd.__init__(self) self.session = '' self.current_user = '' self.server = '' self.ssm = {} self.config = {} self.postcmd(False, '') # make the options available everywhere self.options = options # make the configuration file available everywhere self.config_parser = config_parser # this is used when loading and saving caches self.conf_dir = conf_dir self.history_file = os.path.join(self.conf_dir, 'history') try: # don't split on hyphens or colons during tab completion newdelims = readline.get_completer_delims() newdelims = re.sub(':|-|/', '', newdelims) readline.set_completer_delims(newdelims) if not options.nohistory: try: if os.path.isfile(self.history_file): readline.read_history_file(self.history_file) readline.set_history_length(self.HISTORY_LENGTH) # always write the history file on exit atexit.register(readline.write_history_file, self.history_file) except IOError: logging.error('Could not read history file') # pylint: disable=W0702 except Exception as exc: # pylint: disable=W0702 logging.error("Exception occurred: {}".format(exc)) sys.exit(1)
def __init__(self, forget_history=False): Cmd.__init__(self) self._children = [] self._shell_context = ErtShellContext(self) if not forget_history: self._history_file = os.path.join( os.path.expanduser("~/.ertshell/ertshell.history")) self._init_history() else: self._history_file = None matplotlib.rcParams["interactive"] = True matplotlib.rcParams["mathtext.default"] = "regular" matplotlib.rcParams["verbose.level"] = "helpful" matplotlib.rcParams["verbose.fileo"] = "sys.stderr" try: matplotlib.style.use("ggplot") # available from version 1.4 except AttributeError: pass Debug(self) PlotSettings(self) Cases(self) Workflows(self) Plugins(self) SummaryKeys(self) GenDataKeys(self) GenKWKeys(self) Results(self) Simulations(self) CustomKWKeys(self) AnalysisModule(self) Smoother(self) Observations(self) Export(self) Storage(self) Server(self) self._last_command_failed = False atexit.register(self._cleanup)
def __init__(self, rendezvousAddr=None, controllerNodeId=0, bluetoothAdapter=None): self.lastNetworkId = None Cmd.__init__(self) Cmd.identchars = string.ascii_letters + string.digits + "-" if sys.stdin.isatty(): self.prompt = "chip-device-ctrl > " else: self.use_rawinput = 0 self.prompt = "" DeviceMgrCmd.command_names.sort() self.bleMgr = None self.devCtrl = ChipDeviceCtrl.ChipDeviceController( controllerNodeId=controllerNodeId, bluetoothAdapter=bluetoothAdapter) # If we are on Linux and user selects non-default bluetooth adapter. if sys.platform.startswith("linux") and (bluetoothAdapter is not None): try: self.bleMgr = BleManager(self.devCtrl) self.bleMgr.ble_adapter_select("hci{}".format(bluetoothAdapter)) except Exception as ex: traceback.print_exc() print("Failed to initialize BLE, if you don't have BLE, run chip-device-ctrl with --no-ble") raise ex self.historyFileName = os.path.expanduser( "~/.chip-device-ctrl-history") try: import readline if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") readline.set_completer_delims(" ") try: readline.read_history_file(self.historyFileName) except IOError: pass except ImportError: pass
def __init__(self, lang, lexer, parse_eval, debug=False): """ @lexer is language lexical analyzer @parse_eval is the language interpreter with builtins, runtime, parser etc.. @lang is a descriptive string, @debug the boolean """ Cmd.__init__(self) ## ala-Python like self.banner = """எழில் - ஒரு தமிழ் நிரலாக்க மொழி (Tue Jul 2 20:22:25 EDT 2013) Ezhil : A Tamil Programming Language, (C) 2007-2013 Type "help", "copyright", "credits" or "license" for more information.""" self.lang = lang self.lexer = lexer self.parse_eval = parse_eval self.debug = debug self.line_no = 1 self.env = None ## get the first instance from evaluate_interactive self.cmdloop()
def __init__(self): ''' Initialise the console ''' from dials.util.idials import Controller # Initialise the console base Cmd.__init__(self) # Open a file for history self.command_history = open("command_history", "a") # Create the controller object self.controller = Controller() # Set the prompt to show the current mode self.prompt = "%s >> " % self.controller.get_mode()
def __init__(self, step, location, dirs_to_attempt, client): """ :param step: StepTemplate type :param location: PlayerLocation location """ Cmd.__init__(self) self.passed = True self._step = step self.__command_blocked = False self._location = location self._dirs_to_attempt = dirs_to_attempt # Allows terminal to send message to GUI if needed. self._client = client self.last_cmd_output = "" self._set_prompt() self._autocomplete_dash_characters()
def __init__(self, args, pwdb): Cmd.__init__(self) # manually remove interpreter from command line so that argparse doesn't try to use it # This needs to be removed before the PkInterace init sys.argv.remove("interpreter") pkinterface.PkInterface.__init__(self) self.pwdb = pwdb if pwdb else PasswordDB() self.parser.error = pkparse_error # Hold onto args passed on the command line self.args = args # change our cwd so users can tab complete self._change_pwstore() # We basically need to grab the first argument and ditch it self.parsedargs = {}
def __init__(self, url, dirname, urlfile): """ 设置url、dirname和urlfile,并在一个独立的线程中启动Node服务器 """ Cmd.__init__(self) self.secret = random_string(SECRET_LENGTH) n = Node(url, dirname, self.secret) t = Thread(target=n._start) t.setDaemon(1) t.start() # 让服务器先行一步: sleep(HEAD_START) logging.info(" start server ") logging.info(url) self.server = ServerProxy(url) for line in open(urlfile): line = line.strip() self.server.hello(line) logging.info(" server.hello ") logging.info(line)
def __init__(self): Cmd.__init__(self, 'TAB') Cmd.ruler = '-' print makebold('Welcome to nodectl v' + VERSION + ' [ghimire]. Type "help" for commands description') print 'Searching node... ', whereisnode = Popen(["which", "node"], stdout=PIPE, stderr=PIPE).communicate()[0].rstrip() if (whereisnode): NODEPATH = whereisnode print 'Found at ' + NODEPATH else: print 'Not Found. Exiting...' sys.exit(1) self.prompt = '{' + os.getcwd() + '} % '
def __init__(self, args, recipients_database): #################################################################### Cmd.__init__(self) # Hash of registered subparser actions, mapping string to actual subparser self.actions = {} self.parser = argparse.ArgumentParser( description='Public Key Password Manager') home = os.path.expanduser("~") self.parser.add_argument( '--config', type=str, help= "Path to a PKPass configuration file. Defaults to '~/.pkpassrc'", default=os.path.join(home, '.pkpassrc')) self.subparsers = self.parser.add_subparsers(help='sub-commands', dest='subparser_name') self.recipients_database = recipients_database self.parser.error = pkparse_error card.Card(self) clip.Clip(self) create.Create(self) delete.Delete(self) distribute.Distribute(self) export.Export(self) generate.Generate(self) pkimport.Import(self) pklist.List(self) listrecipients.Listrecipients(self) recover.Recover(self) rename.Rename(self) show.Show(self) update.Update(self) # Hold onto args passed on the command line self.pre_args = args # manually remove interpreter from command line so that argparse doesn't try to use it sys.argv.remove('interpreter') # change our cwd so users can tab complete self._change_pwstore() # We basically need to grab the first argument and ditch it self.parsedargs = {}
def __init__(self, leaf, _id, host, token, *args, **kwargs): """Инициализирует shell. :param leaf: Имя листа :type leaf: str :param _id: Идентификатор листа :type _id: ObjectId :param host: Целевой хост :type host: str :param token: Ключ аутентификации :type token: str """ Cmd.__init__(self, *args, **kwargs) self.__leaf__ = leaf self.__id__ = _id self.host = host self.token = token self.prompt = "[Leaf '{}'] ".format(leaf)
def __init__(self, state): Cmd.__init__(self) self._state = state self._return_code = 1 self.prompt = '>>> ' # Download state self._videos = [] self._video_rsubs = set() # Text query state self._text_query = None self._query_rsubs = set() self.intro = '{name} {version}\n{intro}'.format( name=subdownloader.project.PROJECT_TITLE, version=subdownloader.project.PROJECT_VERSION_FULL_STR, intro=_('Type "help" for more information.'), )
def __init__(self, quantcoin, ip, port): """ Instantiates the Client Shell and setups the Node and the Network interface. The ip and port parameter will be used to register this in the QuantCoin network, so they should be visible in the external network. :param quantcoin: The QuanCoin storages facade. :param ip: This client public IP address. :param port: The port that this client will operate. """ Cmd.__init__(self) self._node_data_lock = threading.Lock() self._block_data_lock = threading.Lock() self._quantcoin = quantcoin self._quantcoin.store_node((ip, port)) self._network = Network(quantcoin) thread.start_new_thread(self._update_job, (ip, port))
def __init__( self, controller, stdin=sys.stdin, script=None, *args, **kwargs ): self.controller = controller # Local variable bindings for py command self.locals = { 'controller': controller } # Attempt to handle input self.inPoller = poll() self.inPoller.register( stdin ) self.inputFile = script Cmd.__init__( self, *args, stdin=stdin, **kwargs ) self.hello_msg() if self.inputFile: self.do_source( self.inputFile ) return self.initReadline() self.run()
def __init__(self, app_name='mkproject', **kwargs): if not os.path.isfile('keyfiles.json'): raise Exception( 'The file "keyfiles.json" was not found. Please run mkcreds.py to generate and save a keyset.' ) kwreader = common.KeywordArgReader('project_name', 'output_file') kwreader.read(**kwargs) self.name = app_name self.project_name = kwreader.get_value('project_name') self.output_file = kwreader.get_value('output_file') self.project_var_specs = [] self.project_var_specs.append( TerraformVarSpec(name='project_name', value=self.project_name)) Cmd.__init__(self) self.prompt = '%s [%s] > ' % (self.name, self.project_name) _ = os.system('clear')
def __init__(self, memobj, config=None, symobj=None): self.extcmds = {} Cmd.__init__(self, stdout=self) self.shutdown = threading.Event() # If they didn't give us a resolver, make one. if symobj == None: symobj = e_resolv.SymbolResolver() if config == None: config = e_config.EnviConfig(defaults=cfgdefs) self.config = config self.memobj = memobj self.symobj = symobj self.canvas = e_canvas.MemoryCanvas(memobj, syms=symobj)
def __init__(self): # SSH 类初始化 self.sshct = SSH_control() # 从pickle中导入 try: with open('data/servers.pickle','r') as fp: self.servers = pickle.load(fp) except: self.servers = [] # 生成初始化的pickle文件 # with open('data/servers.pickle','wb') as fp: # pickle.dump(self.servers,fp) # attack 初始化 self.attack = Attack() # Cmd 初始化 Cmd.__init__(self)
def __init__(self, bridge=None, stdin=sys.stdin): self.prompt = color_str('g', PROMPT_KW) self.bridge = bridge self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output( "***\n Welcome to EasyOVS, type help to see available commands.\n***\n" ) info('*** Starting CLI:\n') while True: try: #if self.isatty(): #quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info('\nInterrupt\n')