def main(): import optparse usage = \ '''%prog [options] <command> For list of the commands available run: $ shakespeare-admin help For more general information run the about or info commands.''' parser = optparse.OptionParser(usage) parser.add_option('-v', '--verbose', dest='verbose', help='Be verbose', action='store_true', default=False) parser.add_option('-c', '--config', dest='config', help='Path to config file', default='development.ini') options, args = parser.parse_args() if len(args) == 0: parser.print_help() return 1 else: cmd = ShakespeareAdmin(verbose=options.verbose, config=options.config) args = ' '.join(args) args = args.replace('-', '_') cmd.onecmd(args)
def main(): import optparse usage = \ '''%prog [options] <command> For list of the commands available run: $ shakespeare-admin help For more general information run the about or info commands.''' parser = optparse.OptionParser(usage) parser.add_option('-v', '--verbose', dest='verbose', help='Be verbose', action='store_true', default=False) parser.add_option('-c', '--config', dest='config', help='Path to config file', default='development.ini') options, args = parser.parse_args() if len(args) == 0: parser.print_help() return 1 else: cmd = ShakespeareAdmin(verbose=options.verbose, config=options.config) args = ' '.join(args) args = args.replace('-','_') cmd.onecmd(args)
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 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(): import optparse usage = \ '''%prog [options] <command> Run about or help for details.''' parser = optparse.OptionParser(usage) parser.add_option('-v', '--verbose', dest='verbose', help='Be verbose', action='store_true', default=False) options, args = parser.parse_args() if len(args) == 0: parser.print_help() return 1 else: cmd = EconAdmin() args = ' '.join(args) cmd.onecmd(args)
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 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 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 run_command(cmd, args): logger.info('run_command() args=%r', args) cmd.onecmd(' '.join(args)) return 0
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(): """ 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(): """ 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 [-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 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 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 enqueue_output(out, host, cmd): for line in iter(out.readline, ''): sys.stdout.write(host) sys.stdout.write(line) cmd.onecmd('')
def main(): """cm. Usage: cm --help cm [--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 = { '--debug': '--debug' in args, '--nosplash': '--nosplash' in args, '-i': '-i' in args} 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 if arguments['COMMAND'] == []: arguments['COMMAND'] = None splash = not arguments['--nosplash'] debug = arguments['--debug'] interactive = arguments['-i'] script = arguments["SCRIPT"] command = arguments["COMMAND"] context = CloudmeshContext(debug=debug, splash=splash) cmd = CloudmeshConsole(context) if script is not None: cmd.do_exec(script) try: if debug: print(">", command) if command is not None: cmd.onecmd(command) except Exception, e: print("ERROR: executing command '{0}'".format(command)) print(70 * "=") print(e) print(70 * "=") Error.traceback()
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 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()
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] """ 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()