Entrypoint of the whole commandline application
342898
def main(args):  ## pylint: disable=too-many-branches
    """"""

    EXNAME = os.path.basename(__file__ if WIN32 else sys.argv[0])

    for ext in (".py", ".pyc", ".exe", "-script.py", "-script.pyc"):  ## pragma: no cover
        if EXNAME.endswith(ext):  ## pragma: no cover
            EXNAME = EXNAME[:-len(ext)]
            break

    USAGE = """\
    Usage:

        %(exname)s {-h|--help}
        %(exname)s {-V|--version}
        %(exname)s [-y|--yaml] [-q|--quiet] ACTION KEY [DEFAULT]
    """ % {"exname": EXNAME}

    HELP = """
    Parses and output chosen subpart or values from YAML input.
    It reads YAML in stdin and will output on stdout it's return value.

%(usage)s

    Options:

        -y, --yaml
                  Output only YAML safe value, more precisely, even
                  literal values will be YAML quoted. This behavior
                  is required if you want to output YAML subparts and
                  further process it. If you know you have are dealing
                  with safe literal value, then you don't need this.
                  (Default: no safe YAML output)

        -q, --quiet
                  In case KEY value queried is an invalid path, quiet
                  mode will prevent the writing of an error message on
                  standard error.
                  (Default: no quiet mode)

        -L, --line-buffer
                  Force parsing stdin line by line allowing to process
                  streamed YAML as it is fed instead of buffering
                  input and treating several YAML streamed document
                  at once. This is likely to have some small performance
                  hit if you have a huge stream of YAML document, but
                  then you probably don't really care about the
                  line-buffering.
                  (Default: no line buffering)

        ACTION    Depending on the type of data you've targetted
                  thanks to the KEY, ACTION can be:

                  These ACTIONs applies to any YAML type:

                    get-type          ## returns a short string
                    get-value         ## returns YAML

                  These ACTIONs applies to 'sequence' and 'struct' YAML type:

                    get-values{,-0}   ## returns list of YAML
                    get-length        ## returns an integer

                  These ACTION applies to 'struct' YAML type:

                    keys{,-0}         ## returns list of YAML
                    values{,-0}       ## returns list of YAML
                    key-values,{,-0}  ## returns list of YAML

                  Note that any value returned is returned on stdout, and
                  when returning ``list of YAML``, it'll be separated by
                  a newline or ``NUL`` char depending of you've used the
                  ``-0`` suffixed ACTION.

        KEY       Identifier to browse and target subvalues into YAML
                  structure. Use ``.`` to parse a subvalue. If you need
                  to use a literal ``.`` or ``\\``, use ``\\`` to quote it.

                  Use struct keyword to browse ``struct`` YAML data and use
                  integers to browse ``sequence`` YAML data.

        DEFAULT   if not provided and given KEY do not match any value in
                  the provided YAML, then DEFAULT will be returned. If no
                  default is provided and the KEY do not match any value
                  in the provided YAML, %(exname)s will fail with an error
                  message.

    Examples:

         ## get last grocery
         cat recipe.yaml       | %(exname)s get-value groceries.-1

         ## get all words of my french dictionary
         cat dictionaries.yaml | %(exname)s keys-0 french.dictionary

         ## get YAML config part of 'myhost'
         cat hosts_config.yaml | %(exname)s get-value cfgs.myhost

    """ % {"exname": EXNAME, "usage": USAGE}

    USAGE = textwrap.dedent(USAGE)
    HELP = textwrap.dedent(HELP)

    opts = _parse_args(args, USAGE, HELP)
    quiet = opts.pop("quiet")

    try:
        first = True
        for output in do(stream=sys.stdin, **opts):
            if first:
                first = False
            else:
                if opts["action"] not in ACTION_SUPPORTING_STREAMING:
                    die("Source YAML is multi-document, "
                        "which doesn't support any other action than %s"
                        % ", ".join(ACTION_SUPPORTING_STREAMING))
                if opts["dump"] is yaml_dump:
                    print("---\n", end="")
                else:
                    print("\0", end="")
                if opts.get("loader") is LineLoader:
                    sys.stdout.flush()

            print(output, end="")
            if opts.get("loader") is LineLoader:
                sys.stdout.flush()
    except (InvalidPath, ActionTypeError) as e:
        if quiet:
            exit(1)
        else:
            die(str(e))
    except InvalidAction as e:
        die("'%s' is not a valid action.\n%s"
            % (e.args[0], USAGE))
919176
def main(
    output_file: str,
    entry_point: Optional[str],
    console_script: Optional[str],
    python: Optional[str],
    site_packages: Optional[str],
    compressed: bool,
    compile_pyc: bool,
    extend_pythonpath: bool,
    pip_args: List[str],
) -> None:
    

    if not pip_args and not site_packages:
        sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES)

    if output_file is None:
        sys.exit(NO_OUTFILE)

    # check for disallowed pip arguments
    for disallowed in DISALLOWED_ARGS:
        for supplied_arg in pip_args:
            if supplied_arg in disallowed:
                sys.exit(
                    DISALLOWED_PIP_ARGS.format(
                        arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed]
                    )
                )

    with TemporaryDirectory() as working_path:
        tmp_site_packages = Path(working_path, "site-packages")

        if site_packages:
            shutil.copytree(site_packages, tmp_site_packages)

        if pip_args:
            # install deps into staged site-packages
            pip.install(["--target", str(tmp_site_packages)] + list(pip_args))

        # if entry_point is a console script, get the callable
        if entry_point is None and console_script is not None:
            try:
                entry_point = find_entry_point(tmp_site_packages, console_script)

            except KeyError:
                if not Path(tmp_site_packages, "bin", console_script).exists():
                    sys.exit(NO_ENTRY_POINT.format(entry_point=console_script))

        # create runtime environment metadata
        env = Environment(
            build_id=str(uuid.uuid4()),
            entry_point=entry_point,
            script=console_script,
            compile_pyc=compile_pyc,
            extend_pythonpath=extend_pythonpath,
        )

        Path(working_path, "environment.json").write_text(env.to_json())

        # create bootstrapping directory in working path
        bootstrap_target = Path(working_path, "_bootstrap")
        bootstrap_target.mkdir(parents=True, exist_ok=True)

        # copy bootstrap code
        copy_bootstrap(bootstrap_target)

        # create the zip
        builder.create_archive(
            Path(working_path),
            target=Path(output_file).expanduser(),
            interpreter=python or _interpreter_path(),
            main="_bootstrap:bootstrap",
            compressed=compressed,
        )
1287588
def main():
    """"""
    import colorama
    import argparse
    import logging
    import sys
    import os

    parser = argparse.ArgumentParser(prog="gulpless",
                                     description="Simple build system.")
    parser.add_argument("-v", "--version",
                        action="version",
                        version="%(prog)s 0.7.6")
    parser.add_argument("-d", "--directory",
                        action="store",
                        default=os.getcwd(),
                        help="Look for `build.py` in this folder (defaults to "
                             "the current directory)")
    parser.add_argument("mode",
                        action="store",
                        choices=["build", "interactive"],
                        default="interactive",
                        metavar="mode",
                        nargs="?",
                        help="If `interactive` (the default), will wait for "
                             "filesystem events and attempt to keep the input "
                             "and output folders in sync. If `build`, it will "
                             "attempt to build all updated files, then exit.")

    args = parser.parse_args()
    os.chdir(args.directory)
    sys.path.append(os.getcwd())

    if os.environ.get("TERM") == "cygwin":
        # colorama doesn't play well with git bash
        del os.environ["TERM"]
        colorama.init()
        os.environ["TERM"] = "cygwin"
    else:
        colorama.init()

    try:
        old, sys.dont_write_bytecode = sys.dont_write_bytecode, True
        import build
    except ImportError:
        sys.exit("No `build.py` found in current folder.")
    finally:
        sys.dont_write_bytecode = old

    try:
        logging.basicConfig(level=build.LOGGING,
                            format="%(message)s")
    except AttributeError:
        logging.basicConfig(level=logging.INFO,
                            format="%(message)s")

    reactor = Reactor(build.SRC, build.DEST)
    for handler in build.HANDLERS:
        reactor.add_handler(handler)
    reactor.run(args.mode == "build")
1291432
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="sloancone",
        tunnel=False
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # 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,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS

    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
646310
def main(args=None):
    
    # Base command line parser. Help is not allowed because command
    # line is parsed in two stages - in the first stage is found setting
    # module of the application, in the second stage are found management
    # command's arguments.
    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '-s', '--settings',
        dest='settings', action='store', type=str, default=None,
        help=_('application settings module')
    )

    # Get settings module
    try:
        settings = get_app_settings(parser, args)
    except ImportError as exc:
        parser.error(_("Invalid application settings module: {}").format(exc))

    # Get management commands and add their arguments into command
    # line parser
    commands = get_management_commands(settings)
    subparsers = parser.add_subparsers(
        dest='action', help=_('specify action')
    )
    for command_cls in six.itervalues(commands):
        subparser = subparsers.add_parser(
            command_cls.name, help=command_cls.help)
        for command_args, kwargs in command_cls.arguments:
            subparser.add_argument(*command_args, **kwargs)

    # Get config class and add its arguments into command line parser
    if settings:
        config_cls = get_config_class(settings)
        if not issubclass(config_cls, Config):
            raise TypeError(
                "Config class must be subclass of the "
                "shelter.core.config.Config")
        for config_args, kwargs in config_cls.arguments:
            parser.add_argument(*config_args, **kwargs)
    else:
        config_cls = Config

    # Add help argument and parse command line
    parser.add_argument(
        '-h', '--help', action='help',
        help=_('show this help message and exit')
    )
    cmdline_args = parser.parse_args(args)
    if not cmdline_args.action:
        parser.error(_('No action'))

    # Run management command
    command_cls = commands[cmdline_args.action]
    if command_cls.settings_required and not settings:
        parser.error(_(
            "Settings module is not defined. You must either set "
            "'SHELTER_SETTINGS_MODULE' environment variable or "
            "'-s/--settings' command line argument."
        ))
    try:
        config = config_cls(settings, cmdline_args)
    except ImproperlyConfiguredError as exc:
        parser.error(str(exc))
    command = command_cls(config)
    try:
        command()
    except Exception:
        traceback.print_exc(file=sys.stderr)
        sys.stderr.flush()
        if multiprocessing.active_children():
            # If main process has children processes, exit immediately without
            # cleaning. It is a workaround, because parent process waits for
            # non-daemon children.
            os._exit(1)
        sys.exit(1)
    sys.exit(0)
1328292
def cmd():
    
    global application

    mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
    if os.path.isfile(mochapyfile):
        cwd_to_sys_path()
        application = import_string("brew")
    else:
        print("-" * 80)
        print("** Missing << 'brew.py' >> @ %s" % CWD)
        print("-" * 80)

    [cmd(cli.command, click) for cmd in Manager.__subclasses__()]
    cli()
320421
def main(args=None):
    """"""

    Config.options, Config.args = parse(args)

    logger()

    if Config.options.aeidon or Config.options.fix:
        start_aeidon()
    else:
        start_srt()

    if Config.options.fix:
        sys.exit(0)

    if not Config.results:
        basenames = [os.path.basename(os.path.abspath(x)) for x in Config.args]
        print('Search of', basenames, 'returned no results.')

        # leave the terminal open long enough to read message
        if Config.options.gui:
            from time import sleep
            sleep(2)
999786
def entrypoint(cls):
    
    if not isinstance(cls, type) or not issubclass(cls, Command):
        raise TypeError(f"inappropriate entrypoint instance of type {cls.__class__}")
    cls._argcmdr_entrypoint_ = True
    return cls
138534
def make_entry_point(patches, original_entry_point):
    
    def entry(argv=None):
        argv = argv if argv is not None else sys.argv[1:]
        return main(
            tuple(patches) + ('--', original_entry_point) + tuple(argv)
        )

    return entry
893504
def main():
    """"""
    conf.init(), db.init(conf.DbPath)
    inqueue = LineQueue(sys.stdin).queue
    outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})()
    if "--quiet" in sys.argv: outqueue = None
    if conf.MouseEnabled:    inqueue.put("mouse_start")
    if conf.KeyboardEnabled: inqueue.put("keyboard_start")
    start(inqueue, outqueue)
707279
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="HMpTy"
    )
    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,))

    if hostFlag:
        dbSettings = {
            'host': hostFlag,
            'user': userFlag,
            'password': passwdFlag,
            'db': dbNameFlag
        }
    elif settings:
        dbSettings = settings["database settings"]

    # CALL FUNCTIONS/OBJECTS
    if index:
        add_htm_ids_to_mysql_database_table(
            raColName=raCol,
            declColName=decCol,
            tableName=tableName,
            dbConn=dbConn,
            log=log,
            primaryIdColumnName=primaryIdCol,
            reindex=forceFlag,
            dbSettings=dbSettings
        )

    if search:
        cs = conesearch(
            log=log,
            dbConn=dbConn,
            tableName=tableName,
            columns=False,
            ra=ra,
            dec=dec,
            radiusArcsec=float(radius),
            separations=True,
            distinct=False,
            sqlWhere=False
        )
        matchIndies, matches = cs.search()
        if not renderFlag:
            print matches.table()
        elif renderFlag == "json":
            print matches.json()
        elif renderFlag == "csv":
            print matches.csv()
        elif renderFlag == "yaml":
            print matches.yaml()
        elif renderFlag == "md":
            print matches.markdown()
        elif renderFlag == "table":
            print matches.markdown()
        elif renderFlag == "mysql":
            print matches.mysql(tableName=resultsTable)

    if level:
        from HMpTy import HTM
        mesh = HTM(
            depth=int(level),
            log=log
        )

        htmids = mesh.lookup_id(ra, dec)
        print htmids[0]

    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
1131914
def console_main():
    """"""
    cmd = main(check=False)
    if cmd is not None:
        sys.exit(cmd.returncode)
239693
def main():
    """"""
    # Initialize logging to the terminal and system log.
    coloredlogs.install(syslog=True)
    # Parse the command line arguments.
    context_opts = {}
    program_opts = {}
    try:
        options, arguments = getopt.getopt(sys.argv[1:], 'fur:vqh', [
            'force', 'use-sudo', 'remote-host=',
            'verbose', 'quiet', 'help',
        ])
        for option, value in options:
            if option in ('-f', '--force'):
                program_opts['force'] = True
            elif option in ('-u', '--use-sudo'):
                context_opts['sudo'] = True
            elif option in ('-r', '--remote-host'):
                context_opts['ssh_alias'] = value
            elif option in ('-v', '--verbose'):
                coloredlogs.increase_verbosity()
            elif option in ('-q', '--quiet'):
                coloredlogs.decrease_verbosity()
            elif option in ('-h', '--help'):
                usage(__doc__)
                sys.exit(0)
            else:
                # Programming error...
                assert False, "Unhandled option!"
        if not arguments:
            usage(__doc__)
            sys.exit(0)
        if len(arguments) != 1:
            raise Exception("Expected a filename as the first and only argument!")
        program_opts['filename'] = arguments[0]
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    # Run the program.
    try:
        # Initialize the execution context.
        program_opts['context'] = create_context(**context_opts)
        # Initialize the program and update the file.
        UpdateDotDee(**program_opts).update_file()
    except Exception as e:
        logger.exception("Encountered unexpected exception, aborting!")
        sys.exit(1)
1034731
async function main() {
  // Initialize the application.
  process.title = 'Which.js';

  // Parse the command line arguments.
  program.name('which')
    .description('Find the instances of an executable in the system path.')
    .version(packageVersion, '-v, --version')
    .option('-a, --all', 'list all instances of executables found (instead of just the first one)')
    .option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
    .arguments('<command>').action(command => program.executable = command)
    .parse(process.argv);

  if (!program.executable) {
    program.outputHelp();
    process.exitCode = 64;
    return;
  }

  // Run the program.
  let executables = await which(program.executable, {all: program.all});
  if (!program.silent) {
    if (!Array.isArray(executables)) executables = [executables];
    for (const path of executables) console.log(path);
  }
}
992478
def main():

    gtselect_keys = ['tmin', 'tmax', 'emin', 'emax', 'zmax', 'evtype', 'evclass',
                     'phasemin', 'phasemax', 'convtype', 'rad', 'ra', 'dec']

    gtmktime_keys = ['roicut', 'filter']

    usage = "usage: %(prog)s [options] "
    description = "Run gtselect and gtmktime on one or more FT1 files.  "
    ""
    parser = argparse.ArgumentParser(usage=usage, description=description)

    add_lsf_args(parser)

    for k in gtselect_keys:

        if k in ['evtype', 'evclass', 'convtype']:
            parser.add_argument('--%s' % k, default=None, type=int, help='')
        else:
            parser.add_argument('--%s' % k, default=None, type=float, help='')

    for k in gtmktime_keys:
        parser.add_argument('--%s' % k, default=None, type=str, help='')

    parser.add_argument('--rock_angle', default=None, type=float, help='')

    parser.add_argument('--outdir', default=None, type=str,
                        help='Path to output directory used when merge=False.')
    parser.add_argument('--output', default=None, type=str,
                        help='Path to output file used when merge=True.')
    parser.add_argument('--scfile', default=None, type=str, help='')

    parser.add_argument('--dry_run', default=False, action='store_true')
    parser.add_argument('--overwrite', default=False, action='store_true')
    parser.add_argument('--merge', default=False, action='store_true',
                        help='Merge input FT1 files into N files where N is determined '
                        'by files_per_split.')

    parser.add_argument('--files_per_split', default=100,
                        type=int, help='Set the number of files to combine in each '
                        'split of the input file list.')

    parser.add_argument('--file_idx_min', default=None,
                        type=int, help='Set the number of files to assign to '
                        'each batch job.')

    parser.add_argument('--file_idx_max', default=None,
                        type=int, help='Set the number of files to assign to '
                        'each batch job.')

    parser.add_argument('files', nargs='+', default=None,
                        help='List of files.')

    args = parser.parse_args()

    batch = vars(args).pop('batch')
    files = vars(args).pop('files')
    args.outdir = os.path.abspath(args.outdir)
    files = [os.path.abspath(f) for f in files]

    ft1_files = get_files(files, ['.fit', '.fits'])
    for i, f in enumerate(ft1_files):
        if re.search('^root\:\/\/', f) is None:
            ft1_files[i] = os.path.abspath(f)

    input_files = []
    output_files = []
    files_idx_min = []
    files_idx_max = []
    opts = []

    if args.file_idx_min is not None and args.file_idx_max is not None:

        files_idx_min = [args.file_idx_min]
        files_idx_max = [args.file_idx_max]
        input_files = [files]
        output_files = [args.output]

    elif args.merge:
        if not args.output:
            raise Exception('No output file defined.')

        nfiles = len(ft1_files)
        njob = int(np.ceil(nfiles / float(args.files_per_split)))
        for ijob, i in enumerate(range(0, nfiles, args.files_per_split)):

            if args.outdir is not None:
                mkdir(args.outdir)
                outdir = os.path.abspath(args.outdir)
            else:
                outdir = os.path.dirname(os.path.dirname(args.output))

            outfile = os.path.splitext(os.path.basename(args.output))[0]
            outfile += '_%03i.fits' % (ijob)
            outfile = os.path.join(outdir, outfile)
            input_files += [files]
            output_files += [outfile]
            files_idx_min += [i]
            files_idx_max += [i + args.files_per_split]
            opts += [vars(args).copy()]
            opts[-1]['output'] = outfile
            opts[-1]['file_idx_min'] = i
            opts[-1]['file_idx_max'] = i + args.files_per_split

    else:
        input_files = ft1_files
        files_idx_min = [i for i in range(len(ft1_files))]
        files_idx_max = [i + 1 for i in range(len(ft1_files))]
        output_files = [os.path.join(
            args.outdir, os.path.basename(x)) for x in ft1_files]
        opts = [vars(args).copy() for x in ft1_files]

    if batch:
        submit_jobs('fermipy-select',
                    input_files, opts, output_files, overwrite=args.overwrite,
                    dry_run=args.dry_run)
        sys.exit(0)

    logger = Logger.configure(os.path.basename(__file__), None, logging.INFO)
    logger.info('Starting.')

    if args.scfile is not None:
        args.scfile = os.path.abspath(args.scfile)

    cwd = os.getcwd()
    user = os.environ['USER']
    tmpdir = tempfile.mkdtemp(prefix=user + '.', dir='/scratch')
    os.chdir(tmpdir)

    logger.info('tmpdir %s', tmpdir)
    logger.info('outdir %s', args.outdir)
    logger.info('output %s', args.output)

    for infiles, outfile, idx_min, idx_max in zip(input_files, output_files,
                                                  files_idx_min, files_idx_max):

        logger.info('infiles %s', pprint.pformat(infiles))
        logger.info('outfile %s', outfile)
        infiles = get_files(infiles, ['.fit', '.fits'])
        if idx_min is not None:
            infiles = infiles[idx_min:idx_max]

        for i, f in enumerate(infiles):

            if re.search('^root\:\/\/', f) is None:
                continue
            os.system('xrdcp %s %s' % (f, f.split('/')[-1]))
            infiles[i] = os.path.join(tmpdir, f.split('/')[-1])

        kw = {k: args.__dict__[k] for k in gtselect_keys}
        if kw['emax'] is None:
            kw['emax'] = 1E6

        create_filelist(infiles, 'list.txt')
        kw['infile'] = 'list.txt'
        kw['outfile'] = 'out.fits'
        staged_outfile = kw['outfile']
        run_gtapp('gtselect', logger, kw)

        kw = {k: args.__dict__[k] for k in gtmktime_keys}
        if kw['roicut'] is None:
            kw['roicut'] = 'no'

        if kw['filter'] is None:
            kw['filter'] = 'DATA_QUAL==1 && LAT_CONFIG==1'
            if args.rock_angle is not None:
                kw['filter'] += ' && ABS(ROCK_ANGLE)<%(rock)s ' % dict(
                    rock=args.rock_angle)
        kw['evfile'] = 'out.fits'
        kw['outfile'] = 'out_filtered.fits'
        if args.scfile is not None:
            kw['scfile'] = args.scfile
            staged_outfile = kw['outfile']
            run_gtapp('gtmktime', logger, kw)

        logger.info('cp %s %s', staged_outfile, outfile)
        shutil.copy(staged_outfile, outfile)

    os.chdir(cwd)
    logger.info('Deleting %s', tmpdir)
    shutil.rmtree(tmpdir)
    logger.info('Done.')
603255
def main():
    """"""
    actions = []
    try:
        # Parse the command line arguments.
        options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
            'convert', 'to-html', 'demo', 'help',
        ])
        # Map command line options to actions.
        for option, value in options:
            if option in ('-c', '--convert', '--to-html'):
                actions.append(functools.partial(convert_command_output, *arguments))
                arguments = []
            elif option in ('-d', '--demo'):
                actions.append(demonstrate_colored_logging)
            elif option in ('-h', '--help'):
                usage(__doc__)
                return
            else:
                assert False, "Programming error: Unhandled option!"
        if not actions:
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    for function in actions:
        function()
1316337
def main(argv=None):
    ''' 

    '''
    from intake.cli.bootstrap import main as _main

    return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv)