Start an oct project

    :param Namespace args: the commande-line arguments
488953
def run(args):
    
    kwargs = vars(args)

    if 'func' in kwargs:
        del kwargs['func']

    project_path = kwargs.pop('project_path')
    config = configure(project_path, kwargs.get('config_file'))

    output_dir = kwargs.pop('output_dir', None) or generate_output_path(args, project_path)

    stats_handler.init_stats(output_dir, config)

    topic = args.publisher_channel or uuid.uuid4().hex
    print("External publishing topic is %s" % topic)

    start_hq(output_dir, config, topic, **kwargs)

    if not args.no_results:
        process_results(output_dir, config)

    copy_config(project_path, output_dir)
    print('done.\n')
10994
def start_interpreter(self, namespace):
        """"""
        self.clear()
        
        if self.interpreter is not None:
            self.interpreter.closing()
        self.interpreter = Interpreter(namespace, self.exitfunc,
                                       SysOutput, WidgetProxy,
                                       get_debug_level())
        self.interpreter.stdout_write.data_avail.connect(self.stdout_avail)
        self.interpreter.stderr_write.data_avail.connect(self.stderr_avail)
        self.interpreter.widget_proxy.sig_set_readonly.connect(self.setReadOnly)
        self.interpreter.widget_proxy.sig_new_prompt.connect(self.new_prompt)
        self.interpreter.widget_proxy.sig_edit.connect(self.edit_script)
        self.interpreter.widget_proxy.sig_wait_input.connect(self.wait_input)
        if self.multithreaded:
            self.interpreter.start()
        
        # Interpreter banner
        banner = create_banner(self.message)
        self.write(banner, prompt=True)

        # Initial commands
        for cmd in self.commands:
            self.run_command(cmd, history=False, new_prompt=False)
                
        # First prompt
        self.new_prompt(self.interpreter.p1)
        self.refresh.emit()

        return self.interpreter
234581
def run_init(args):
    
    root = args.root
    if root is None:
        root = '.'
    root = os.path.abspath(root)

    project_data = _get_package_data()
    project_name = project_data['project_name']

    directories = [os.path.join(root, 'bin'),
                   os.path.join(root, 'docs'),
                   os.path.join(root, 'tests'),
                   os.path.join(root, project_name),
                   ]
    for dir_path in directories:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    script_paths = [os.path.join(root, 'README.md'),
                    os.path.join(root, 'tests/__init__.py'),
                    ]
    for script_path in script_paths:
        if not os.path.exists(script_path):
            os.mknod(script_path)

    copy_samples = [(resource_filename('mpu', 'package/templates/tox.ini.txt'),
                     os.path.join(root, 'tox.ini')),
                    (resource_filename('mpu',
                                       'package/templates/setup.cfg.txt'),
                     os.path.join(root, 'setup.cfg')),
                    (resource_filename('mpu',
                                       'package/templates/setup.py.txt'),
                     os.path.join(root, 'setup.py')),
                    (resource_filename('mpu',
                                       'package/templates/_version.py.txt'),
                     os.path.join(root, project_name + '/_version.py')),
                    (resource_filename('mpu',
                                       'package/templates/coveragerc.txt'),
                     os.path.join(root, '.coveragerc')),
                    (resource_filename('mpu', 'package/templates/init.py.txt'),
                     os.path.join(root, project_name + '/__init__.py')),
                    ]
    translate = {'[[project_name]]': project_data['project_name'],
                 '[[license]]': project_data['license'],
                 '[[author]]': project_data['author'],
                 '[[email]]': project_data['email'],
                 }
    for source, destination in copy_samples:
        if not os.path.exists(destination):
            copyfile(source, destination)
            _adjust_template(destination, translate)
280461
def main():
    
    from datetime import datetime

    # Initialize Command-Line and User-Config Settings, Log
    # -----------------------------------------------------

    beg_time = datetime.now()
    # Process command-line arguments to determine action
    # If no subcommand (e.g. 'import') is given, returns 'None' --> exit
    args, sub_clargs = load_command_line_args()
    if args is None:
        return

    # Create a logging object
    log = load_log(args)

    # Run configuration/setup interactive script
    if args.command == 'setup':
        setup_user_config(log)
        return

    # Make sure configuration file exists, or that's what we're doing
    # (with the 'setup' subcommand)
    if not os.path.isfile(_CONFIG_PATH):
        raise RuntimeError("'{}' does not exist.  "
                           "Run `astrocats setup` to configure."
                           "".format(_CONFIG_PATH))

    git_vers = get_git()
    title_str = "Astrocats, version: {}, SHA: {}".format(__version__, git_vers)
    log.warning("\n\n{}\n{}\n{}\n".format(title_str, '=' * len(title_str),
                                          beg_time.ctime()))

    # Load the user settings from the home directory
    args = load_user_config(args, log)

    # Choose Catalog and Operation(s) to perform
    # ------------------------------------------
    mod_name = args.command
    log.debug("Importing specified module: '{}'".format(mod_name))
    # Try to import the specified module
    try:
        mod = importlib.import_module('.' + mod_name, package='astrocats')
    except Exception as err:
        log.error("Import of specified module '{}' failed.".format(mod_name))
        log_raise(log, str(err), type(err))

    # Run the `main.main` method of the specified module
    log.debug("Running `main.main()`")
    mod.main.main(args, sub_clargs, log)

    end_time = datetime.now()
    log.warning("\nAll complete at {}, After {}".format(end_time, end_time -
                                                        beg_time))
    return
965705
def _run_bunny(args):
    
    main_file, json_file, project_name = _get_main_and_json(args.directory)
    work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "bunny_work"))
    flags = ["-b", work_dir]
    log_file = os.path.join(work_dir, "%s-bunny.log" % project_name)
    if os.path.exists(work_dir):
        caches = [os.path.join(work_dir, d) for d in os.listdir(work_dir)
                  if os.path.isdir(os.path.join(work_dir, d))]
        if caches:
            flags += ["--cache-dir", max(caches, key=os.path.getmtime)]
    if args.no_container:
        _remove_bcbiovm_path()
        flags += ["--no-container"]
    cmd = ["rabix"] + flags + [main_file, json_file]
    with utils.chdir(work_dir):
        _run_tool(cmd, not args.no_container, work_dir, log_file)
47303
def execute(self, argv=None):
        
        if self.completion:
            self.autocomplete()
        parser = self.get_parser()
        namespace = parser.parse_args(argv)
        if hasattr(namespace, 'func'):
            self.run_command(namespace)
905604
def start():
    
    pool = gevent.threadpool.ThreadPool(len(ENTRYPOINTS))
    for entrypoint, callback, args, kwargs in ENTRYPOINTS:
        cname = callback.__name__
        #1. Retrieve the class which owns the callback
        for name, klass in inspect.getmembers(sys.modules[callback.__module__], inspect.isclass):
            if hasattr(klass, cname):
                service_name = name.lower()
                break
        #2.Start the entrypoint
        callback = getattr(klass(), cname)
        kwargs.update({'service':service_name, 'callback':callback, 'callback_name': cname})
        LOGGER.info('Start service %s[%s].', service_name.capitalize(), cname)
        obj = entrypoint(*args, **kwargs)
        pool.spawn(obj.start, *args, **kwargs)
    pool.join()
    return True
1219109
def parse_args(self, args=None, namespace=None):
        
        self._expand_prefixed_files(args)
        return super(CLICommandParser, self).parse_args(args)
895330
def create_args(line, namespace):
    
    args = []
    # Using shlex.split handles quotes args and escape characters.
    for arg in shlex.split(line):
      if not arg:
         continue
      if arg[0] == '$':
        var_name = arg[1:]
        if var_name in namespace:
          args.append((namespace[var_name]))
        else:
          raise Exception('Undefined variable referenced in command line: %s' % arg)
      else:
        args.append(arg)
    return args
610195
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")
75273
def execute(self, args):
        
        import colorama

        self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_CREATE, args=args)
        cmd_tbl = self.commands_loader.load_command_table(args)
        command = self._rudimentary_get_command(args)
        self.cli_ctx.invocation.data['command_string'] = command
        self.commands_loader.load_arguments(command)

        self.cli_ctx.raise_event(EVENT_INVOKER_POST_CMD_TBL_CREATE, cmd_tbl=cmd_tbl)
        self.parser.load_command_table(self.commands_loader)
        self.cli_ctx.raise_event(EVENT_INVOKER_CMD_TBL_LOADED, parser=self.parser)

        arg_check = [a for a in args if a not in ['--verbose', '--debug']]
        if not arg_check:
            self.cli_ctx.completion.enable_autocomplete(self.parser)
            subparser = self.parser.subparsers[tuple()]
            self.help.show_welcome(subparser)
            return CommandResultItem(None, exit_code=0)

        if args[0].lower() == 'help':
            args[0] = '--help'

        self.cli_ctx.completion.enable_autocomplete(self.parser)

        self.cli_ctx.raise_event(EVENT_INVOKER_PRE_PARSE_ARGS, args=args)
        parsed_args = self.parser.parse_args(args)
        self.cli_ctx.raise_event(EVENT_INVOKER_POST_PARSE_ARGS, command=parsed_args.command, args=parsed_args)

        self._validation(parsed_args)

        # save the command name (leaf in the tree)
        self.data['command'] = parsed_args.command
        cmd = parsed_args.func
        if hasattr(parsed_args, 'cmd'):
            parsed_args.cmd = cmd
        deprecations = getattr(parsed_args, '_argument_deprecations', [])
        if cmd.deprecate_info:
            deprecations.append(cmd.deprecate_info)

        params = self._filter_params(parsed_args)

        # search for implicit deprecation
        path_comps = cmd.name.split()[:-1]
        implicit_deprecate_info = None
        while path_comps and not implicit_deprecate_info:
            implicit_deprecate_info = resolve_deprecate_info(self.cli_ctx, ' '.join(path_comps))
            del path_comps[-1]

        if implicit_deprecate_info:
            deprecate_kwargs = implicit_deprecate_info.__dict__.copy()
            deprecate_kwargs['object_type'] = 'command'
            del deprecate_kwargs['_get_tag']
            del deprecate_kwargs['_get_message']
            deprecations.append(ImplicitDeprecated(**deprecate_kwargs))

        colorama.init()
        for d in deprecations:
            print(d.message, file=sys.stderr)
        colorama.deinit()

        cmd_result = parsed_args.func(params)
        cmd_result = todict(cmd_result)

        event_data = {'result': cmd_result}
        self.cli_ctx.raise_event(EVENT_INVOKER_TRANSFORM_RESULT, event_data=event_data)
        self.cli_ctx.raise_event(EVENT_INVOKER_FILTER_RESULT, event_data=event_data)

        return CommandResultItem(event_data['result'],
                                 exit_code=0,
                                 table_transformer=cmd_tbl[parsed_args.command].table_transformer,
                                 is_query_active=self.data['query_active'])
646668
def _run_cwltool(args):
    
    main_file, json_file, project_name = _get_main_and_json(args.directory)
    work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cwltool_work"))
    tmp_dir = utils.safe_makedir(os.path.join(work_dir, "tmpcwl"))
    log_file = os.path.join(work_dir, "%s-cwltool.log" % project_name)
    os.environ["TMPDIR"] = tmp_dir
    flags = ["--tmpdir-prefix", tmp_dir, "--tmp-outdir-prefix", tmp_dir]
    if args.no_container:
        _remove_bcbiovm_path()
        flags += ["--no-container", "--preserve-environment", "PATH", "--preserve-environment", "HOME"]
    cmd = ["cwltool"] + flags + args.toolargs + ["--", main_file, json_file]
    with utils.chdir(work_dir):
        _run_tool(cmd, not args.no_container, work_dir, log_file=log_file)
1060421
def parse(self, line, namespace=None):
    
    try:
      if namespace is None:
        ipy = IPython.get_ipython()
        namespace = ipy.user_ns
      args = CommandParser.create_args(line, namespace)
      return self.parse_args(args)
    except Exception as e:
      print(str(e))
      return None
6974
def main(args=None):
    
    # parse args
    if args is None:
        args = parse_args(sys.argv[1:])

    # set logging level
    if args.verbose > 1:
        set_log_debug()
    elif args.verbose == 1:
        set_log_info()

    outpath = os.path.abspath(os.path.expanduser(args.out_dir))
    cachepath = os.path.abspath(os.path.expanduser(args.cache_dir))
    cache = DiskDataCache(cache_path=cachepath)

    if args.user:
        args.PROJECT = _pypi_get_projects_for_user(args.user)

    if args.query:
        DataQuery(args.project_id, args.PROJECT, cache).run_queries(
            backfill_num_days=args.backfill_days)
    else:
        logger.warning('Query disabled by command-line flag; operating on '
                       'cached data only.')
    if not args.generate:
        logger.warning('Output generation disabled by command-line flag; '
                       'exiting now.')
        raise SystemExit(0)
    for proj in args.PROJECT:
        logger.info('Generating output for: %s', proj)
        stats = ProjectStats(proj, cache)
        outdir = os.path.join(outpath, proj)
        OutputGenerator(proj, stats, outdir).generate()
332661
def main():
    
    try:
        # A bit of a hack: We want to load the plugins (specified via the mode
        # and health parameter) in order to add their arguments to the argument
        # parser. But this means we first need to look into the CLI arguments
        # to find them ... before looking at the arguments. So we first perform
        # a manual search through the argument list for this purpose only.
        args = sys.argv[1:]

        # Loading the watcher plugin
        mode_name = utils.param_extract(args, "-m", "--mode", default=None)
        if mode_name:
            watcher_plugin_class = \
                load_plugin(mode_name, watcher.WATCHER_DEFAULT_PLUGIN_MODULE)
        else:
            watcher_plugin_class = None

        # Loading the health monitor plugin
        health_check_name = \
            utils.param_extract(args, "-H", "--health",
                                default=monitor.MONITOR_DEFAULT_PLUGIN)
        if health_check_name:
            health_plugin_class = \
                load_plugin(health_check_name,
                            monitor.MONITOR_DEFAULT_PLUGIN_MODULE)
        else:
            health_plugin_class = None

        # Provide complete arg parsing for vpcrouter and all plugin classes.
        conf = _parse_args(sys.argv[1:],
                           watcher_plugin_class, health_plugin_class)

        if not health_plugin_class or not watcher_plugin_class:
            logging.error("Watcher plugin or health monitor plugin class "
                          "are missing.")
            sys.exit(1)

        _setup_logging(conf)

        # If we are on an EC2 instance then some data is already available to
        # us. The return data items in the meta data match some of the command
        # line arguments, so we can pass this through to the parser function to
        # provide defaults for those parameters. Specifically: VPC-ID and
        # region name.
        if not conf['vpc_id'] or not conf['region_name']:
            meta_data = get_ec2_meta_data()
            if 'vpc_id' not in meta_data or 'region_name' not in meta_data:
                logging.error("VPC and region were not explicitly specified "
                              "and can't be auto-discovered.")
                sys.exit(1)
            else:
                conf.update(meta_data)

        try:
            info_str = "vpc-router (%s): mode: %s (%s), " \
                       "health-check: %s (%s)" % \
                       (vpcrouter.__version__,
                        conf['mode'], watcher_plugin_class.get_version(),
                        health_check_name, health_plugin_class.get_version())
            logging.info("*** Starting %s ***" % info_str)
            CURRENT_STATE.versions = info_str

            http_srv = http_server.VpcRouterHttpServer(conf)
            CURRENT_STATE._vpc_router_http = http_srv

            watcher.start_watcher(conf,
                                  watcher_plugin_class, health_plugin_class)
            http_srv.stop()
            logging.info("*** Stopping vpc-router ***")
        except Exception as e:
            import traceback
            traceback.print_exc()
            logging.error(e.message)
            logging.error("*** Exiting")
    except Exception as e:
        print "\n*** Error: %s\n" % e.message

    sys.exit(1)
263115
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="tastic"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/tastic/tastic.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if sort or archive:

        ws = workspace(
            log=log,
            settings=settings,
            fileOrWorkspacePath=pathToFileOrWorkspace
        )
    if sort:
        ws.sort()
    if archive:
        ws.archive_done()

    if sync:
        tp = syncc(
            log=log,
            settings=settings,
            workspaceRoot=pathToWorkspace,
            workspaceName=workspaceName,
            syncFolder=pathToSyncFolder,
            editorialRootPath=editorialRootPath,
            includeFileTags=fileTagsFlag
        )
        tp.sync()

    if reminders:
        r = reminderss(
            log=log,
            settings=settings
        )
        r.import_list(
            listName=listName,
            pathToTaskpaperDoc=pathToTaskpaperDoc
        )

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
769963
def start(self, *args):
        

        if self.volumes: 
            volumes = " --bind " + " --bind ".join(self.volumes)
        else:
            volumes = ""
        
        self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
        utils.xrun("singularity instance.start", 
                        list(args) + [volumes,
#                        "-c",
                        self.image, self.name])

        self.status = "created"

        return 0