Setup the parser and call the command function
484543
def main():
    
    parser = argparse.ArgumentParser(description='Longclaw CLI')
    subparsers = parser.add_subparsers()
    start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project')
    start.add_argument('project_name', help='Name of the project')
    start.set_defaults(func=create_project)

    build = subparsers.add_parser('build', help='Build the front-end assets for Longclaw')
    build.set_defaults(func=build_assets)

    args = parser.parse_args()

    # Python 3 lost the default behaviour to fall back to printing
    # help if a subparser is not selected.
    # See: https://bugs.python.org/issue16308
    # So we must explicitly catch the error thrown on py3 if
    # no commands given to longclaw
    try:
        args.func(args)
    except AttributeError:
        parser.print_help()
        sys.exit(0)
314641
def run(self):
        '''
        
        '''

        # Parse the stdin into a global event object
        stdin = self.read_stdin()
        self.event = self.read_event(stdin)

        # Prepare global settings
        self.settings = get_settings()
        self.api_settings = self.get_api_settings()

        # Prepare command line arguments and
        self.parser = argparse.ArgumentParser()

        # set up the 2.x to 1.x event mapping argument
        self.parser.add_argument("--map-v2-event-into-v1",
                                 action="store_true",
                                 default=False,
                                 dest="v2event")

        if hasattr(self, 'setup'):
            self.setup()
        (self.options, self.remain) = self.parser.parse_known_args()

        # map the event if required
        if (self.options.v2event or
                os.environ.get("SENSU_MAP_V2_EVENT_INTO_V1")):
            self.event = map_v2_event_into_v1(self.event)

        # Filter (deprecated) and handle
        self.filter()
        self.handle()
57819
def execute(self):
        
        # Ensure that we have commands registered
        if not self.commands or self._parser is None:
            raise NotImplementedError(
                "No commands registered with this program!"
            )

        # Handle input from the command line
        args = self.parser.parse_args()                # Parse the arguments

        try:

            handle_default_args(args)                  # Handle the default args

            if not hasattr(args, 'func'):              # Handle no subcommands
                self.parser.print_help()
                self.exit(0)

            msg = args.func(args)                      # Call the default function
            msg = "{}\n".format(msg) if msg else ''    # Format the message
            self.exit(0, msg)                          # Exit cleanly with message

        except Exception as e:
            if hasattr(args, 'traceback') and args.traceback:
                traceback.print_exc()

            msg = color.format(str(e), color.RED)
            self.exit(1, msg)
1176268
def add_commands(self):
        
        self.parser.add_argument(
            '-d',
            action="count",
            **self.config.default.debug.get_arg_parse_arguments())
246591
def set_subcommands(func, parser):
    
    if hasattr(func, '__subcommands__') and func.__subcommands__:
        sub_parser = parser.add_subparsers(
            title=SUBCOMMANDS_LIST_TITLE, dest='subcommand',
            description=SUBCOMMANDS_LIST_DESCRIPTION.format(
                func.__cmd_name__),
            help=func.__doc__)
        for sub_func in func.__subcommands__.values():
            parser = get_parser(sub_func, sub_parser)
            for args, kwargs in get_shared(sub_func):
                parser.add_argument(*args, **kwargs)
    else:
        for args, kwargs in get_shared(func):
            parser.add_argument(*args, **kwargs)
155224
function main(content, callback) {
  parser(content, function(error, result) {
    if (error) {
      callback(error);
    } else {
      callback(null, result);
    }
  });
}
1330394
def setup(self):
        """"""
        if not isinstance(self.filePath, str):
            raise TypeError("File path is not a string!")
        if self.controller is None:
            raise ValueError("Command controller hasn't been specified!")
89703
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="rockfinder",
        defaultSettingsFile=True
    )
    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 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,))

    # CALL FUNCTIONS/OBJECTS

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockfinder/rockfinder.yaml"
        cmd = """open %(filepath)s""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        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
        return

    if where and orbfitFlag:
        from rockfinder import orbfit_ephemeris
        eph = orbfit_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            settings=settings,
            verbose=extraFlag
        )
    else:
        from rockfinder import jpl_horizons_ephemeris
        eph = jpl_horizons_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            verbose=extraFlag
        )

    dataSet = list_of_dictionaries(
        log=log,
        listOfDictionaries=eph
    )
    # xfundamentals-render-list-of-dictionaries

    output = dataSet.table(filepath=None)
    if csv:
        output = dataSet.csv(filepath=None)
    elif json:
        output = dataSet.json(filepath=None)
    elif yaml:
        output = dataSet.yaml(filepath=None)
    elif md:
        output = dataSet.markdown(filepath=None)
    elif rst:
        output = dataSet.reST(filepath=None)

    print output

    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
663951
def _add_command(parser, subparser_fn, handler, cell_required=False,
                 cell_prohibited=False):
  
  sub_parser = subparser_fn(parser)
  sub_parser.set_defaults(func=lambda args, cell: _dispatch_handler(
      args, cell, sub_parser, handler, cell_required=cell_required,
      cell_prohibited=cell_prohibited))
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")
314371
def add_cmd(self, name, help=None, func=None):
        
        if self.subparsers is None:
            self.subparsers = self.add_subparsers(
                title="sub-commands",
                help=help or 'sub-commands',
            )

        parser = self.subparsers.add_parser(
            name,
            help=help,
        )
        if func is not None:
            parser.set_defaults(_func=func)
        return parser
297592
def main(arguments=None):
    
    # setup the command-line util settings

    dev_flag = False

    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="rockAtlas"
    )
    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/rockAtlas/rockAtlas.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 bookkeeping:
        from rockAtlas.bookkeeping import bookkeeper
        bk = bookkeeper(
            log=log,
            settings=settings,
            fullUpdate=fullFlag
        )
        bk.clean_all()

    if astorb:
        from rockAtlas.orbital_elements import astorb
        oe = astorb(
            log=log,
            settings=settings
        )
        oe.refresh()

    if pyephem:

        from rockAtlas.positions import pyephemPositions
        pyeph = pyephemPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        pyeph.get(singleSnapshot=oneFlag)

    if orbfit:
        from rockAtlas.positions import orbfitPositions
        oe = orbfitPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        oe.get(singleExposure=oneFlag)

    if cache:
        from rockAtlas.phot import download
        data = download(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        data.get(days=days)

    if dophot:
        from rockAtlas.phot import dophotMatch
        dp = dophotMatch(
            log=log,
            settings=settings
        )
        dp.get()

    if cycle:
        from rockAtlas.phot import download
        from rockAtlas.positions import pyephemPositions
        from rockAtlas.positions import orbfitPositions
        from rockAtlas.phot import dophotMatch
        from fundamentals.mysql import readquery

        # INITIAL ACTIONS
        # SETUP ALL DATABASE CONNECTIONS
        from rockAtlas import database
        db = database(
            log=log,
            settings=settings
        )
        dbConns, dbVersions = db.connect()
        atlas3DbConn = dbConns["atlas3"]
        atlas4DbConn = dbConns["atlas4"]
        atlasMoversDBConn = dbConns["atlasMovers"]

        while True:

            if dev_flag:
                o = " and dev_flag = 1"
            else:
                o = " "

            sqlQuery = u"""
                select distinct floor(mjd) from (
select mjd from atlas_exposures where dophot_match = 0 %(o)s
union all
select mjd from day_tracker where processed = 0 %(o)s) as a;
            """ % locals()
            rows = readquery(
                log=log,
                sqlQuery=sqlQuery,
                dbConn=atlasMoversDBConn,
                quiet=False
            )

            if len(rows) == 0:
                if dev_flag:
                    print "Processing of the ATLAS development dataset is now complete and up to date"
                else:
                    print "Processing of ATLAS data is now complete and up to date"
                break

            start_time = time.time()

            data = download(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            data.get(days=days)

            print "%d seconds to download ATLAS cache of %s days\n" % (time.time() - start_time, days)
            start_time = time.time()

            pyeph = pyephemPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            pyeph.get()

            print "%d seconds to generate pyephem snapshots\n" % (time.time() - start_time,)
            start_time = time.time()

            oe = orbfitPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            oe.get()

            print "%d seconds to generate orbfit positions\n" % (time.time() - start_time,)
            start_time = time.time()

            dp = dophotMatch(
                log=log,
                settings=settings
            )
            dp.get()

            print "%d seconds to extract dophot measurements\n" % (time.time() - start_time,)
            start_time = time.time()

    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
724867
def main():
    """"""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    appengine.register_commands(subparsers)
    requirements.register_commands(subparsers)
    pylint.register_commands(subparsers)

    args = parser.parse_args()
    args.func(args)
852963
def cmdline(argv, rules=None, config=None, **kwargs):
    """"""
    parser = Parser(rules, **kwargs)
    if config is not None: parser.loadrc(config)
    return parser.parse(argv).result
213881
def parse():
    """"""

    # Build the list of subcommand modules
    modnames = [mod for (_, mod, _)
                in pkgutil.iter_modules(payu.subcommands.__path__,
                                        prefix=payu.subcommands.__name__ + '.')
                if mod.endswith('_cmd')]

    subcmds = [importlib.import_module(mod) for mod in modnames]

    # Construct the subcommand parser
    parser = argparse.ArgumentParser()
    parser.add_argument('--version', action='version',
                        version='payu {0}'.format(payu.__version__))

    subparsers = parser.add_subparsers()

    for cmd in subcmds:
        cmd_parser = subparsers.add_parser(cmd.title, **cmd.parameters)
        cmd_parser.set_defaults(run_cmd=cmd.runcmd)

        for arg in cmd.arguments:
            cmd_parser.add_argument(*arg['flags'], **arg['parameters'])

    # Display help if no arguments are provided
    if len(sys.argv) == 1:
        parser.print_help()
    else:
        args = vars(parser.parse_args())
        run_cmd = args.pop('run_cmd')
        run_cmd(**args)
899672
def do_setup(self, arg, arguments):
        
        if arguments["init"]:
            Console.ok("Initialize cmd3.yaml file")

            from cmd3.yaml_setup import create_cmd3_yaml_file
            force = arguments["--force"]
            create_cmd3_yaml_file(force=force)
690620
def register(self, command):
        
        command = command()
        if command.name in self.commands:
            raise ConsoleError(
                "Command %s already registered!" % command.name
            )

        command.create_parser(self.subparsers)
        self.commands[command.name] = command