def test_file_with_missing_final_nl(self): input = io.StringIO("print test\nprint test2") output = io.StringIO() cmd = self.simplecmd(stdin=input, stdout=output) cmd.use_rawinput = False cmd.cmdloop() self.assertMultiLineEqual(output.getvalue(), ("(Cmd) test\n" "(Cmd) test2\n" "(Cmd) "))
def main(): if len(sys.argv) < 2: print('Must supply an argument') return if sys.argv[1] == 'insert': filename = sys.argv[2] filename = os.path.abspath(filename) print('Inserting file:', filename) index = Index(INDEX_LOCATION) index.insert(filename) index.addtag(filename, 'TAGME', '') index.writeindex() elif sys.argv[1] == 'dump': index = Index(INDEX_LOCATION) index.dump() elif sys.argv[1] == 'dumptag': tagname = sys.argv[2] index = Index(INDEX_LOCATION) index.dumptag(tagname) elif sys.argv[1] == 'addtag': filename = sys.argv[2] filename = os.path.abspath(filename) tagname = sys.argv[3] if len(sys.argv) > 4: value = sys.argv[4] else: value = '' index = Index(INDEX_LOCATION) index.addtag(filename, tagname, value) index.writeindex() elif sys.argv[1] == 'cmd': cmd = IndexCommands() cmd.cmdloop() else: print('Unknown option:', sys.argv[1])
def main(): parser = argparse.ArgumentParser() parser.add_argument('--host', type=str, nargs='?', default='localhost') parser.add_argument('--port', type=int, nargs='?', default=8000) args = parser.parse_args() cmd = Cmd(args.host, args.port) cmd.cmdloop()
def main(): plugins = get_plugins("./plugins") name = "CmCli" (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.activate() cmd.cmdloop()
def main(): """ The main routine. """ # Instantiate the app app = CmdlineApplication() caOption = Option("-C", "--ca", action = "store_true", dest = "is_ca_mode", default = 0, help = "Use CA mode for this invocation of the certificate manager.") idOption = Option("-I", "--id", action = "store_false", dest = "is_ca_mode", default = 0, help = "Use ID mode for this invocation of the certificate manager.") forceOption = Option("-f", "--force", action = "store_true", dest = "force_overwrite", default = 0, help = "Overwrite existing files.") app.AddCmdLineOption(caOption) app.AddCmdLineOption(idOption) app.AddCmdLineOption(forceOption) try: args = app.Initialize("CertificateManager") except Exception: sys.exit(0) cmd = CertMgrCmdProcessor(app.GetCertificateManager(), app.GetLog()) # # If no args were passed, start up the command-driver # cert mgr. # if app.GetOption("is_ca_mode"): cmd.setCAMode() if len(args) == 0: cmd.cmdloop() else: # # Otherwise, process a single command from teh command line. # cmd.setInteractive(0) cmd.setForceOverwrite(app.GetOption("force_overwrite")) mycmd = args[0] + " " + " ".join(map(lambda a: '"' + a + '"', args[1:])) print mycmd cmd.onecmd(mycmd)
def handleInput(self, char): #log.msg('handling %s' % repr(char)) options = self.options if char in ('\n', '\r'): self.escapeMode = 1 self.write(char) elif self.escapeMode == 1 and char == options['escape']: self.escapeMode = 2 elif self.escapeMode == 2: self.escapeMode = 1 # so we can chain escapes together if char == '.': # disconnect log.msg('disconnecting from escape') stopConnection() return elif char == '\x1a': # ^Z, suspend def _(): self.ssh.rawmode.leave() sys.stdout.flush() sys.stdin.flush() os.kill(os.getpid(), signal.SIGTSTP) self.ssh.rawmode.enter() reactor.callLater(0, _) return elif char == 'R': # rekey connection log.msg('rekeying connection') self.conn.transport.sendKexInit() return elif char == ':': # enter command mode old = self.stdio try: self.ssh.rawmode.leave() try: cmd = CmdShell(self) cmd.cmdloop('.oO( sshx )Oo.') except: char = None log.err("cmd.cmdloop() failed") self.ssh.rawmode.enter() finally: self.stdio = old elif char == '#': # display connections self.stdio.write('\r\nThe following connections are open:\r\n') channels = self.conn.channels.keys() channels.sort() for channelId in channels: self.stdio.write(' #%i %s\r\n' % (channelId, str(self.conn.channels[channelId]))) return if char is not None: self.write('~' + char) else: self.escapeMode = 0 self.write(char)
def do_edit(self, text): cmd = None if self.binary.type == Type.ELF: cmd = ELFConsole(self.binary, self.__cprinter) elif self.binary.type == Type.PE: cmd = PEConsole(self.binary, self.__cprinter) elif self.binary.type == Type.MACH_O: cmd = MachOConsole(self.binary, self.__cprinter) else: self.printError('This type is currently not supported: %s' % self.binary.type) return if cmd: cmd.cmdloop()
def test_input_reset_at_EOF(self): input = io.StringIO("print test\nprint test2") output = io.StringIO() cmd = self.simplecmd2(stdin=input, stdout=output) cmd.use_rawinput = False cmd.cmdloop() self.assertMultiLineEqual(output.getvalue(), ("(Cmd) test\n" "(Cmd) test2\n" "(Cmd) *** Unknown syntax: EOF\n")) input = io.StringIO("print \n\n") output = io.StringIO() cmd.stdin = input cmd.stdout = output cmd.cmdloop() self.assertMultiLineEqual(output.getvalue(), ("(Cmd) \n" "(Cmd) \n" "(Cmd) *** Unknown syntax: EOF\n"))
def main(): """ """ try: opts, args = getopt.getopt(sys.argv[1:], "hif:", ["help", "interactive", "file="]) except getopt.GetoptError: usage() sys.exit(2) script_file = None interactive = False for option, argument in opts: if option in ("-h", "--help"): usage() sys.exit() if option in ("-f", "--file"): script_file = argument if option in ("-i", "--interactive"): interactive = True plugin_path = os.path.join(os.path.dirname(__file__),'plugins') plugins = get_plugins(plugin_path) name = "CmCli" (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.version() cmd.activate() cmd.do_exec(script_file) if is_subcmd(opts, args): try: user_cmd = " ".join(args) print ">", user_cmd cmd.onecmd(user_cmd) except: print "'%s' is not recognized" % user_cmd elif not script_file or interactive: cmd.cmdloop()
def main(): """ Fonction de main pour le serveur """ # parsage des arguments de la ligne de commande args = ServerArgumentParser().parse_args() # mise a jour du port d'envoi config.server.send_port = args.port print __description__ # # ajout de la version du fs en override si présent # if not args.version is None: # setattr(config.server, "fsversion", args.version) cmd = ServerCmd() # vérification de la présence du dossier de données et création if not os.path.exists(config.server.save_dir): try: os.mkdir(config.server.save_dir) except e: print "error: impossible de créer le dossier de données, sortie ..."; return 1 # lancement en mode interactif (Shell) if args.shell: cmd.cmdloop() # lancement non interactif else: # renseignement du test à lancer if not args.bench_test is None: print ">> Lancement du benchmark '%s'" % args.bench_test cmd.onecmd('run ' + args.bench_test) else: print "error: aucun benchmark renseigné (à choisir dans la liste des \ fichiers de 'config/tests/'"; return 1 return 0
def main(): parser = argparse.ArgumentParser(description='FIX Gateway') parser.add_argument('--debug', action='store_true', help='Run in debug mode') parser.add_argument('--host', '-H', default='localhost', help="IP address or hostname of the FIX-Gateway Server") parser.add_argument('--port', '-P', type=int, default=3490, help="Port number to use for FIX-Gateway Server connection") parser.add_argument('--prompt', '-p', default='FIX: ', help="Command line prompt") parser.add_argument('--file', '-f', nargs=1, metavar='FILENAME', help="Execute commands within file") parser.add_argument('--execute','-x', nargs='+', help='Execute command') parser.add_argument('--interactive', '-i', action='store_true', help='Keep running after commands are executed') args, unknown_args = parser.parse_known_args() log = logging.getLogger() if args.debug: log.level = logging.DEBUG c = netfix.Client(args.host, args.port) c.connect() cmd = Command(c) # If commands are beign redirected or piped we set the prompt to nothing if sys.stdin.isatty(): cmd.prompt = args.prompt else: cmd.prompt = "" if args.execute: s = " ".join(args.execute) cmd.onecmd(s) if not args.interactive: exit(0) cmd.cmdloop() c.disconnect()
def run_interactive(cmd): logger.info('run_interactive()') cmd.cmdloop() return 0
def main(): """ OnTalk OnConsole. Usage: onconsole [-q] help onconsole [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ echo = False try: arguments = docopt(main.__doc__, help=True) if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: pprint(arguments) print(arguments) except: script_file = None interactive = False arguments = {'-b': True, 'COMMAND': [' '.join(sys.argv[1:])]} cmd.Cmd.set_verbose(echo) cmd.Cmd.activate() cmd.set_verbose(echo) cmd.set_debug(properties["debug"]) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: Console.error("") Console.error("ERROR: executing command '{0}'".format(user_cmd)) Console.error("") print (70 * "=") print(e) print (70 * "=") print(traceback.format_exc()) if interactive: cmd.cmdloop()
def main(options, args): cmd = qacmd(options) cmd.cmdloop()
def run(cls, *modules, **karg): "start interactive mode." #logging.basicConfig() global history_file, preference_file, pref, log from os import environ as ENV fqcn = cls.__name__ argv = karg.get('argv', sys.argv) last_history = karg.get('last_history') sn = cn = str(fqcn).split('.')[-1] pos = fqcn.rfind('.') mn = fqcn[0:pos] if pos > 0 else '__main__' mod = __import__(mn) global verbose, interactive if 'DEBUG' in ENV: verbose = True if verbose: print("argv: %s" % " ".join(argv), file=sys.stderr) preference_name = os.path.expanduser('~/.%s/%s' % (appname, cn)) opts, args = getopt(argv[1:], 'vp:D:', ( 'verbose', 'define=', 'preference=', )) defs = [] for opt, optarg in opts: if opt in ('-v', '--verbose'): verbose = True elif opt in ('-D', '--define'): key, value = optarg.split('=') defs.append((key, value)) elif opt in ('-p', '--preference'): preference_name = optarg pt = optarg.find(':') if pt > 0: preference_name = optarg[:pt] sn = optarg[pt+1:] verbose = True pref = INIPreference(preference_name) try: pref.load() except: pass pref.set_section(sn) for key, value in defs: pref.store(key, value) if last_history: save_history(last_history) home = os.path.expanduser('~') history_file = pref.value('history-file', os.path.join(home, 'logs', '%s.history' % cn)) if os.path.exists(history_file): load_history() if verbose: pref.store('console-log-level', 'DEBUG') log = get_logger(cn, pref=pref) mod.pref = pref mod.log = log cmd = cls() cmd.pref = pref for mod in modules: mod.pref = pref mod.log = log c0 = os.path.basename(argv[0]) if '-' in c0 and not c0.endswith('.py'): subcmd = c0[c0.find('-')+1:] args.insert(0, subcmd) if args: line = _arg_join(args) if verbose: puts('args', args, file=err) interactive = False try: rc = cmd.onecmd(line) except Exception as e: rc = 3 elog = log.exception if verbose else log.error elog('%s while execute\n %s', e, line) except KeyboardInterrupt: rc = 4 syserr.write('Interrupted.\n') if verbose: puts('rc: ', rc, file=err) if last_history: # カスケード呼び出しされている history_file = last_history if os.path.exists(history_file): load_history() return rc sys.exit(rc) interactive = True while True: try: cmd.cmdloop() save_history() if last_history: if os.path.exists(last_history): load_history(last_history) history_file = last_history pref.save() break except KeyboardInterrupt as e: # 割り込みをかけても中断させない if verbose: log.exception('%s while cmdloop', e) else: syserr.write('Interrupted.\n')
def activate_status(self): print "Active:", self.active def activate(self, plugins): d = dir(self) result = [] for key in d: if key.startswith("activate_"): result.append(key) print result for key in result: print "> %s" % key.replace("_"," ") exec("self.%s()" % key) """ import sys import cmd import readline from cyberaide import load_plugins from cyberaide import make_cmd_class from cyberaide import DynamicCmd plugins = ["foo", "bar","activate"] name = "CmCli" (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.activate(plugin_objects) cmd.cmdloop()
return if (len(new_line) == 2): if (new_line[1] in lst_cmd2 and new_line[0] in cls_lst): if (new_line[1] == 'all'): HBNBCommand.do_all(self, new_line[0]) return if (new_line[1] == 'create'): HBNBCommand.do_create(self, new_line[0]) return if (new_line[1] == 'count'): HBNBCommand.do_count(self, new_line[0]) return if (len(new_line) == 3): if (new_line[1] in lst_cmd3 and new_line[0] in cls_lst): if (new_line[1] == 'show'): HBNBCommand.do_show(self, new_line[0] + " " + new_line[2]) if (new_line[1] == 'destroy'): HBNBCommand.do_destroy(self, new_line[0] + " " + new_line[2]) return if __name__ == '__main__': cmd = HBNBCommand() cmd.prompt = '(hbnb) ' cmd.cmdloop()
def main(): """ OnTalk OnConsole. Usage: onconsole [-q] help onconsole [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ echo = False try: arguments = docopt(main.__doc__, help=True) if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: pprint(arguments) print(arguments) except: script_file = None interactive = False arguments = {'-b': True, 'COMMAND': [' '.join(sys.argv[1:])]} cmd.Cmd.set_verbose(echo) cmd.Cmd.activate() cmd.set_verbose(echo) cmd.set_debug(properties["debug"]) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: Console.error("") Console.error("ERROR: executing command '{0}'".format(user_cmd)) Console.error("") print(70 * "=") print(e) print(70 * "=") print(traceback.format_exc()) if interactive: cmd.cmdloop()
def main(): """cm. Usage: cm [--file=SCRIPT] [--interactive] [--quiet] [COMMAND ...] cm [-f SCRIPT] [-i] [-q] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the scipt --interactive -i After start keep the shell interactive, otherwise quit --quiet -q Surpress some of the informational messages. """ # __version__ = pkg_resources.require("cmd3")[0].version #arguments = docopt(main.__doc__, help=True, version=__version__) arguments = docopt(main.__doc__, help=True) script_file = arguments['--file'] interactive = arguments['--interactive'] quiet = arguments['--quiet'] def get_plugins_from_dir(dir_path, classbase): """dir_path/classbase/plugins""" if dir_path == "sys": dir_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'plugins')) dir_plugins = get_plugins(dir_path) return {"dir": dir_path, "plugins": dir_plugins, "class": classbase} if dir_path == ".": dir_path = os.path.expanduser( os.path.expandvars(os.path.join(os.getcwd(), 'plugins'))) dir_plugins = get_plugins(dir_path) return {"dir": dir_path, "plugins": dir_plugins, "class": classbase} else: dir_path = os.path.expanduser(os.path.expandvars(dir_path)) prefix = "{0}/{1}".format(dir_path, classbase) user_path = "{0}/plugins".format(prefix) create_dir(user_path) create_file("{0}/__init__.py".format(prefix)) create_file("{0}/plugins/__init__.py".format(prefix)) sys.path.append(os.path.expanduser(dir_path)) dir_plugins = get_plugins(user_path) return {"dir": dir_path, "plugins": dir_plugins, "class": classbase} plugins = [] plugins.append(dict(get_plugins_from_dir("sys", "cmd3"))) plugins.append(dict(get_plugins_from_dir("~/.futuregrid", "cmd3local"))) #plugins.append(dict(get_plugins_from_dir (".", "dot"))) for plugin in plugins: sys.path.append(os.path.expanduser(plugin['dir'])) sys.path.append("../..") sys.path.append(".") sys.path.append("..") for plugin in plugins: plugin['class'] = plugin['class'] + ".plugins" pprint(plugins) pprint(sys.path) # sys.exit() name = "CmCli" # # not yet quite what i want, but falling back to a flatt array # (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.version() # cmd.set_verbose(quiet) cmd.activate() cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) print ">", user_cmd cmd.onecmd(user_cmd) except: print "'%s' is not recognized" % user_cmd elif not script_file or interactive: cmd.cmdloop()
def start_cli(ctrl): cmd = CLI() cmd.set_controller(ctrl) cmd.cmdloop() ctrl.teardown()
def main(): """cm. Usage: cm --help cm [--echo] [--debug] [--nosplash] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] --nosplash do not show the banner [default: False] """ def manual(): print(main.__doc__) args = sys.argv[1:] arguments = { '--echo': '--echo' in args, '--help': '--help' in args, '--debug': '--debug' in args, '--nosplash': '--nosplash' in args, '-i': '-i' in args} echo = arguments["--echo"] if arguments['--help']: manual() sys.exit() for a in args: if a in arguments: args.remove(a) arguments['COMMAND'] = [' '.join(args)] commands = arguments["COMMAND"] if len(commands) > 0: if ".cm" in commands[0]: arguments["SCRIPT"] = commands[0] commands = commands[1:] else: arguments["SCRIPT"] = None arguments["COMMAND"] = ' '.join(commands) if arguments["COMMAND"] == '': arguments["COMMAND"] = None # noinspection PySimplifyBooleanCheck if arguments['COMMAND'] == []: arguments['COMMAND'] = None splash = not arguments['--nosplash'] debug = arguments['--debug'] interactive = arguments['-i'] script = arguments["SCRIPT"] command = arguments["COMMAND"] context = CloudmeshContext( interactive=interactive, debug=debug, echo=echo, splash=splash) cmd = CloudmeshConsole(context) if script is not None: cmd.do_exec(script) try: if echo: print("cm>", command) if command is not None: cmd.precmd(command) stop = cmd.onecmd(command) cmd.postcmd(stop, command) except Exception as e: print("ERROR: executing command '{0}'".format(command)) print(70 * "=") print(e) print(70 * "=") Error.traceback() if interactive or (command is None and script is None): cmd.cmdloop()
def main(): """cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ # __version__ = pkg_resources.require("cmd3")[0].version # arguments = docopt(main.__doc__, help=True, version=__version__) echo = False try: arguments = docopt(main.__doc__, help=True) # fixing the help parameter parsing if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: pprint(arguments) except: script_file = None interactive = False arguments = {} arguments['-b'] = True arguments['COMMAND'] = [' '.join(sys.argv[1:])] plugins = [] plugins.append(dict(get_plugins_from_dir("sys", "cmd3"))) # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) modules = [ 'cloudmesh_cmd3.plugins', 'cloudmesh_docker.plugins', 'cloudmesh_slurm.plugins', 'cloudmesh_deploy.plugins' ] for module_name in modules: # print "INSTALL", module_name try: plugins.append(dict(get_plugins_from_module(module_name))) except: #print "WARNING: could not find", module_name pass #sys.exit() #plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # plugins.append(dict(get_plugins_from_dir (".", "dot"))) for plugin in plugins: sys.path.append(os.path.expanduser(plugin['dir'])) sys.path.append("../..") sys.path.append(".") sys.path.append("..") for plugin in plugins: plugin['class'] = plugin['class'] + ".plugins" # pprint(plugins) # pprint(sys.path) # sys.exit() name = "CmCli" # # not yet quite what i want, but falling back to a flatt array # (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.get_version() cmd.set_verbose(echo) cmd.activate() cmd.set_verbose(echo) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: print() print("ERROR: executing command '{0}'".format(user_cmd)) print() print(e) print(traceback.format_exc()) if interactive: cmd.cmdloop()
def main(): """cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ # __version__ = pkg_resources.require("cmd3")[0].version # arguments = docopt(main.__doc__, help=True, version=__version__) arguments = docopt(main.__doc__, help=True) # fixing the help parameter parsing if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: print(arguments) plugins = [] plugins.append(dict(get_plugins_from_dir("sys", "cmd3"))) # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) modules = ['cloudmesh_cmd3.plugins', 'cloudmesh_docker.plugins', 'cloudmesh_slurm.plugins'] for module_name in modules: # print "INSTALL", module_name try: plugins.append(dict(get_plugins_from_module(module_name))) except: #print "WARNING: could not find", module_name pass #sys.exit() #plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # plugins.append(dict(get_plugins_from_dir (".", "dot"))) for plugin in plugins: sys.path.append(os.path.expanduser(plugin['dir'])) sys.path.append("../..") sys.path.append(".") sys.path.append("..") for plugin in plugins: plugin['class'] = plugin['class'] + ".plugins" # pprint(plugins) # pprint(sys.path) # sys.exit() name = "CmCli" # # not yet quite what i want, but falling back to a flatt array # (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.get_version() cmd.set_verbose(echo) cmd.activate() cmd.set_verbose(echo) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: print() print("ERROR: executing command '{0}'".format(user_cmd)) print() print(e) print(traceback.format_exc()) if interactive: cmd.cmdloop()
def main(): """ The main routine. """ # Instantiate the app app = CmdlineApplication() caOption = Option( "-C", "--ca", action="store_true", dest="is_ca_mode", default=0, help="Use CA mode for this invocation of the certificate manager.") idOption = Option( "-I", "--id", action="store_false", dest="is_ca_mode", default=0, help="Use ID mode for this invocation of the certificate manager.") forceOption = Option("-f", "--force", action="store_true", dest="force_overwrite", default=0, help="Overwrite existing files.") app.AddCmdLineOption(caOption) app.AddCmdLineOption(idOption) app.AddCmdLineOption(forceOption) try: args = app.Initialize("CertificateManager") except Exception: sys.exit(0) cmd = CertMgrCmdProcessor(app.GetCertificateManager(), app.GetLog()) # # If no args were passed, start up the command-driver # cert mgr. # if app.GetOption("is_ca_mode"): cmd.setCAMode() if len(args) == 0: cmd.cmdloop() else: # # Otherwise, process a single command from teh command line. # cmd.setInteractive(0) cmd.setForceOverwrite(app.GetOption("force_overwrite")) mycmd = args[0] + " " + " ".join(map(lambda a: '"' + a + '"', args[1:])) print mycmd cmd.onecmd(mycmd)
def main(): """cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ echo = False try: arguments = docopt(main.__doc__, help=True) # fixing the help parameter parsing if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: pprint(arguments) except: script_file = None interactive = False arguments = {'-b': True, 'COMMAND': [' '.join(sys.argv[1:])]} plugins = [] plugins.append(dict(get_plugins_from_dir("sys", "cmd3"))) # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # if not os.path.exists(path_expand( "~/.cloudmesh/cmd3.yaml")): # from cmd3.plugins.shell_core import create_cmd3_yaml_file # create_cmd3_yaml_file() create_cmd3_yaml_file(force=False, verbose=False) filename = path_expand("~/.cloudmesh/cmd3.yaml") try: module_config = ConfigDict(filename=filename) modules = module_config["cmd3"]["modules"] properties = module_config["cmd3"]["properties"] except: modules = ['cloudmesh_cmd3.plugins'] for module_name in modules: #print ("INSTALL", module_name) try: plugins.append(dict(get_plugins_from_module(module_name))) except: # print("WARNING: could not find", module_name) pass # sys.exit() # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # plugins.append(dict(get_plugins_from_dir (".", "dot"))) for plugin in plugins: sys.path.append(os.path.expanduser(plugin['dir'])) sys.path.append("../..") sys.path.append(".") sys.path.append("..") for plugin in plugins: plugin['class'] += ".plugins" # pprint(plugins) # pprint(sys.path) # sys.exit() name = "CmCli" # # not yet quite what i want, but falling back to a flatt array # (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.set_verbose(echo) cmd.activate() cmd.set_verbose(echo) cmd.set_debug(properties["debug"]) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception as e: Console.error("") Console.error("ERROR: executing command '{0}'".format(user_cmd)) Console.error("") print(70 * "=") print(e) print(70 * "=") print(traceback.format_exc()) if interactive: cmd.cmdloop() elif not script_file or interactive: cmd.cmdloop()
import sys class Command(cmd.Cmd): prompt = 'What do you do? ' def do_d(self, args): "Roll dice. Usage: 'd <nb>'" nb = int(args) rolls = [random.randint(1, 6) for x in xrange(nb)] successes = sum(1 for roll in rolls if roll >= 4) print "Rolls:", rolls print "Success: %d" % successes def do_quit(self, args): "Simply exits" print print "Bye" sys.exit() do_EOF = do_quit do_exit = do_quit if __name__ == '__main__': cmd = Command() try: cmd.cmdloop('Please...') except KeyboardInterrupt, e: sys.exit('\nbye')
def main(): """cm. Usage: cm --help cm [--echo] [--debug] [--nosplash] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] --nosplash do not show the banner [default: False] """ def manual(): print(main.__doc__) args = sys.argv[1:] arguments = { '--echo': '--echo' in args, '--help': '--help' in args, '--debug': '--debug' in args, '--nosplash': '--nosplash' in args, '-i': '-i' in args } echo = arguments["--echo"] if arguments['--help']: manual() sys.exit() for a in args: if a in arguments: args.remove(a) arguments['COMMAND'] = [' '.join(args)] commands = arguments["COMMAND"] if len(commands) > 0: if ".cm" in commands[0]: arguments["SCRIPT"] = commands[0] commands = commands[1:] else: arguments["SCRIPT"] = None arguments["COMMAND"] = ' '.join(commands) if arguments["COMMAND"] == '': arguments["COMMAND"] = None # noinspection PySimplifyBooleanCheck if arguments['COMMAND'] == []: arguments['COMMAND'] = None splash = not arguments['--nosplash'] debug = arguments['--debug'] interactive = arguments['-i'] script = arguments["SCRIPT"] command = arguments["COMMAND"] context = CloudmeshContext(interactive=interactive, debug=debug, echo=echo, splash=splash) cmd = CloudmeshConsole(context) if script is not None: cmd.do_exec(script) try: if echo: print("cm>", command) if command is not None: cmd.precmd(command) stop = cmd.onecmd(command) cmd.postcmd(stop, command) except Exception as e: print("ERROR: executing command '{0}'".format(command)) print(70 * "=") print(e) print(70 * "=") Error.traceback() if interactive or (command is None and script is None): cmd.cmdloop()
def main(): """cm. Usage: cm --help cm [--debug] [--nosplash] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] --nosplash do not show the banner [default: False] """ try: arg = docopt(main.__doc__, help=True) if arg['--help']: print(main.__doc__) sys.exit() # fixing the help parameter parsing # arguments['COMMAND'] = ['help'] # arguments['help'] = 'False' script_file = arg['--file'] except: script_file = None interactive = False arguments = sys.argv[1:] arg = { '--debug': '--debug' in arguments, '--nosplash': '--nosplash' in arguments, '-i': '-i' in arguments} for a in arg: if arg[a]: arguments.remove(a) arg['COMMAND'] = [' '.join(arguments)] splash = not arg['--nosplash'] debug = arg['--debug'] interactive = arg['-i'] context = CloudmeshContext(debug=debug, splash=splash) cmd = CloudmeshConsole(context) if len(arg['COMMAND']) > 0: try: user_cmd = " ".join(arg['COMMAND']) if debug: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: print("ERROR: executing command '{0}'".format(user_cmd)) print(70 * "=") print(e) print(70 * "=") print(traceback.format_exc()) if interactive: cmd.cmdloop()
def main(): """cm. Usage: cm --help cm [--debug] [--nosplash] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] --nosplash do not show the banner [default: False] """ try: arg = docopt(main.__doc__, help=True) if arg['--help']: print(main.__doc__) sys.exit() # fixing the help parameter parsing # arguments['COMMAND'] = ['help'] # arguments['help'] = 'False' script_file = arg['--file'] except: script_file = None interactive = False arguments = sys.argv[1:] arg = { '--debug': '--debug' in arguments, '--nosplash': '--nosplash' in arguments, '-i': '-i' in arguments} for a in arg: if arg[a]: arguments.remove(a) arg['COMMAND'] = [' '.join(arguments)] splash = not arg['--nosplash'] debug = arg['--debug'] interactive = arg['-i'] context = CloudmeshContext(debug=debug, splash=splash) cmd = CloudmeshConsole(context) # TODO: check if cludmesh_yaml exists and if not create it # also creat .cloudmesh dir if it not exists """ from cloudmesh_client.common import cloudmesh_yaml create_cmd3_yaml_file(force=False, verbose=False) filename = cloudmesh_yaml try: module_config = ConfigDict(filename=filename) modules = module_config["cmd3"]["modules"] properties = module_config["cmd3"]["properties"] except: modules = ['cloudmesh_cmd3.plugins'] for module_name in modules: #print ("INSTALL", module_name) try: plugins.append(dict(get_plugins_from_module(module_name))) except: # print "WARNING: could not find", module_name pass """ # if script_file is not None: # cmd.do_exec(script_file) if len(arg['COMMAND']) > 0: user_cmd = None try: user_cmd = " ".join(arg['COMMAND']) if debug: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception as e: print("ERROR: executing command '{0}'".format(user_cmd)) print(70 * "=") print(e) print(70 * "=") Error.traceback() if interactive: cmd.cmdloop() elif not script_file or interactive: cmd.cmdloop()
def execute(self): Env.RTestInstance = self if self.args.env_only: Defaults.verbose = 2 env = Env(testName='manual test env') if self.args.interactive_debugger: while env.isUp(): time.sleep(1) else: cmd = MyCmd(env) cmd.cmdloop() env.stop() return done = 0 startTime = time.time() if self.args.interactive_debugger and len(self.loader.tests) != 1: print(self.tests) print( Colors.Bred( 'only one test can be run on interactive-debugger use -t')) sys.exit(1) jobs = Queue() for test in self.loader: jobs.put(test, block=False) def run_jobs(jobs, results, port): Defaults.port = port done = 0 while True: try: test = jobs.get(timeout=0.1) except Exception as e: break with self.envScopeGuard(): if test.is_class: test.initialize() Defaults.curr_test_name = test.name try: obj = test.create_instance() except unittest.SkipTest: self.printSkip(test.name) continue except Exception as e: self.printException(e) self.addFailure(test.name + " [__init__]") continue failures = 0 before = getattr(obj, 'setUp', None) after = getattr(obj, 'tearDown', None) for subtest in test.get_functions(obj): failures += self._runTest( subtest, prefix='\t', numberOfAssertionFailed=failures, before=before, after=after) done += 1 else: self._runTest(test) done += 1 self.takeEnvDown(fullShutDown=True) # serialized the results back results.put({ 'done': done, 'failures': self.testsFailed }, block=False) results = Queue() if self.parallelism == 1: run_jobs(jobs, results, Defaults.port) else: processes = [] currPort = Defaults.port for i in range(self.parallelism): p = Process(target=run_jobs, args=(jobs, results, currPort)) currPort += 30 # safe distance for cluster and replicas processes.append(p) p.start() for p in processes: p.join() # join results while True: try: res = results.get(timeout=0.1) except Exception as e: break done += res['done'] self.testsFailed.extend(res['failures']) endTime = time.time() print(Colors.Bold('Test Took: %d sec' % (endTime - startTime))) print( Colors.Bold( 'Total Tests Run: %d, Total Tests Failed: %d, Total Tests Passed: %d' % (done, self.getTotalFailureCount(), done - self.getTotalFailureCount()))) if self.testsFailed: print(Colors.Bold('Failed Tests Summary:')) for group, failures in self.testsFailed: print('\t' + Colors.Bold(group)) if not failures: print('\t\t' + Colors.Bred( 'Exception raised during test execution. See logs')) for failure in failures: print('\t\t' + failure) sys.exit(1)
def main(): try: config = INIConfig(open(CONF_FILE)) except Exception: print("Error: Could not open configuration file '{}', exiting".format( CONF_FILE)) exit(ERR) # Get list of modules to load, verify the required ones exist if not isinstance(config.modules.modules, str) or not config.modules.modules: print("Error: No modules listed in configuration file, exiting") exit(ERR) modules = [m.strip() for m in config.modules.modules.split(',')] for reqd in REQD_MODULES: if not reqd in modules: print("Error: required module '{}' not set to be loaded, exiting". format(reqd)) exit(ERR) # Get system params, verify their sanity system_params = dict() system_params['station_id'] = config.station.stationid system_params['station_pass'] = config.station.stationpass system_params['server_host'] = config.server.host system_params['server_port'] = config.server.port for key, value in system_params.items(): if not isinstance(value, str): print( "Error: param '{}' not appropriately defined in the configuration file, exiting." .format(key)) exit(ERR) system_params['server_port'] = int(system_params['server_port']) # Load modules sys.path.append(MODPATH) loadedmods = dict() for module in modules: modsource = MOD_PREFIX + module try: Mod = import_module(modsource) ModObj = Mod.start(config, ) loadedmods[module] = ModObj except Exception as e: if module in REQD_MODULES: print( "Could not load required module '{}': {}, exiting.".format( module, e)) exit(ERR) else: print("Warning: could not load module '{}': {}.".format( module, e)) print("Loaded modules: {}".format(loadedmods.keys())) print("") for devnum, dev in loadedmods['devices'].devs.iteritems(): serial = dev.serial cmdline = eval("config.startup.startup_{}".format(serial)) if isinstance(cmdline, str): try: module, args = cmdline.split(' ', 1) except Exception: module = cmdline.strip() args = None if module in REQD_MODULES or module not in loadedmods.keys(): continue if args == '': args = None continue if loadedmods[module].run(devnum, args, system_params, loadedmods): loadedmods['devices'].occupy(devnum, module, args) # pseudo-devices devnum = PSEUDO_DEVNUM_BASE while True: cmdline = eval("config.startup.startup_{}".format(devnum)) if isinstance(cmdline, str): try: module, args = cmdline.split(' ', 1) except Exception: module = cmdline.strip() args = None if module in REQD_MODULES or module not in loadedmods.keys(): continue if args == '': args = None continue if loadedmods[module].run(devnum, args, system_params, loadedmods): loadedmods['devices'].occupy(devnum, module, args, pseudo=True) devnum += 1 else: break cmd = Interpreter() cmd.system_params = system_params cmd.loadedmods = loadedmods cmd.cmdloop()
def cli(self): cmd = TaskmasterCmd(self, 'Hello>$ ') cmd.cmdloop() return 0
def main(): display_welcome() cmd = CmdParse(parser.shellParser()) cmd.cmdloop()
def run(cls, first_commands=None): """ Convenience function to run a command loop """ with cls(first_commands) as cmd: cmd.cmdloop()
def main(): """cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, otherwise quit [default: False] -b surpress the printing of the banner [default: False] """ echo = False try: arguments = docopt(main.__doc__, help=True) # fixing the help parameter parsing if arguments['help']: arguments['COMMAND'] = ['help'] arguments['help'] = 'False' script_file = arguments['--file'] interactive = arguments['-i'] echo = arguments['-v'] if echo: pprint(arguments) except: script_file = None interactive = False arguments = {'-b': True, 'COMMAND': [' '.join(sys.argv[1:])]} plugins = [] plugins.append(dict(get_plugins_from_dir("sys", "cmd3"))) # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # if not os.path.exists(path_expand( "~/.cloudmesh/cmd3.yaml")): # from cmd3.plugins.shell_core import create_cmd3_yaml_file # create_cmd3_yaml_file() create_cmd3_yaml_file(force=False, verbose=False) filename = path_expand("~/.cloudmesh/cmd3.yaml") try: module_config = ConfigDict(filename=filename) modules = module_config["cmd3"]["modules"] properties = module_config["cmd3"]["properties"] except: modules = ['cloudmesh_cmd3.plugins'] for module_name in modules: #print ("INSTALL", module_name) try: plugins.append(dict(get_plugins_from_module(module_name))) except: # print "WARNING: could not find", module_name pass # sys.exit() # plugins.append(dict(get_plugins_from_dir("~/.cloudmesh", "cmd3local"))) # plugins.append(dict(get_plugins_from_dir (".", "dot"))) for plugin in plugins: sys.path.append(os.path.expanduser(plugin['dir'])) sys.path.append("../..") sys.path.append(".") sys.path.append("..") for plugin in plugins: plugin['class'] += ".plugins" # pprint(plugins) # pprint(sys.path) # sys.exit() name = "CmCli" # # not yet quite what i want, but falling back to a flatt array # (cmd, plugin_objects) = DynamicCmd(name, plugins) cmd.set_verbose(echo) cmd.activate() cmd.set_verbose(echo) cmd.set_debug(properties["debug"]) if arguments['-b']: cmd.set_banner("") if script_file is not None: cmd.do_exec(script_file) if len(arguments['COMMAND']) > 0: try: user_cmd = " ".join(arguments['COMMAND']) if echo: print(">", user_cmd) cmd.onecmd(user_cmd) except Exception, e: Console.error("") Console.error("ERROR: executing command '{0}'".format(user_cmd)) Console.error("") print (70 * "=") print(e) print (70 * "=") print(traceback.format_exc()) if interactive: cmd.cmdloop()
self.prettypath(self.wallet, self.folder, e), entry.value) def help_get(self): return "get the value behind the given entry in the current folder and wallet" def do_ch_pwd(self,cmd): self.wallet.changePassword() def help_ch_pwd(self): return "change the password for the current wallet" def do_set(self, entry): if entry in self.folder: print "overriding existing value!" entry = self.folder.openEntry(entry) entry.value = input_default( self.prettypath(self.wallet,self.folder, entry)+"=" , entry.value) def help_set(self): return "set or override the value for the entry in teh current folder and wallet" if __name__ == "__main__": cmd = KWalletShell() cmd.cmdloop("kwallet started..., enjoy")
def execute(self): Env.RTestInstance = self if self.args.env_only: Env.defaultVerbose = 2 env = Env(testName='manual test env') if self.args.interactive_debugger: while env.isUp(): time.sleep(1) else: cmd = MyCmd(env) cmd.cmdloop() env.stop() return done = 0 startTime = time.time() if self.args.interactive_debugger and len(self.loader.tests) != 1: print(self.tests) print( Colors.Bred( 'only one test can be run on interactive-debugger use -t')) sys.exit(1) for test in self.loader: with self.envScopeGuard(): if test.is_class: try: obj = test.create_instance() except unittest.SkipTest: self.printSkip() continue except Exception as e: self.printException(e) self.addFailure(test.name + " [__init__]") continue print(Colors.Cyan(test.name)) failures = 0 before = getattr(obj, 'setUp', None) after = getattr(obj, 'tearDown', None) for subtest in test.get_functions(obj): failures += self._runTest( subtest, prefix='\t', numberOfAssertionFailed=failures, before=before, after=after) done += 1 else: self._runTest(test) done += 1 self.takeEnvDown(fullShutDown=True) endTime = time.time() print(Colors.Bold('Test Took: %d sec' % (endTime - startTime))) print( Colors.Bold( 'Total Tests Run: %d, Total Tests Failed: %d, Total Tests Passed: %d' % (done, self.getTotalFailureCount(), done - self.getTotalFailureCount()))) if self.testsFailed: print(Colors.Bold('Failed Tests Summary:')) for group, failures in self.testsFailed: print('\t' + Colors.Bold(group)) if not failures: print('\t\t' + Colors.Bred( 'Exception raised during test execution. See logs')) for failure in failures: print('\t\t' + failure) sys.exit(1)
import cmd import sys class Command(cmd.Cmd): prompt = 'What do you do? ' def do_d(self, args): "Roll dice. Usage: 'd <nb>'" nb = int(args) rolls = [random.randint(1, 6) for x in xrange(nb)] successes = sum(1 for roll in rolls if roll >= 4) print "Rolls:", rolls print "Success: %d" % successes def do_quit(self, args): "Simply exits" print print "Bye" sys.exit() do_EOF = do_quit do_exit = do_quit if __name__ == '__main__': cmd = Command() try: cmd.cmdloop('Please...') except KeyboardInterrupt, e: sys.exit('\nbye')