*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
486314
def main(arguments=None):
    
    from astrocalc.coords import unit_conversion
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="CRITICAL",
        options_first=True,
        projectName="astrocalc"
    )
    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 coordflip:

        if cartesianFlag:
            converter = unit_conversion(
                log=log
            )
            x, y, z = converter.ra_dec_to_cartesian(
                ra="23 45 21.23232",
                dec="+01:58:5.45341"
            )
            print x, y, z
            return

        try:
            ra = float(ra)
            dec = float(dec)
            degree = True
        except Exception, e:
            degree = False

        if degree is True:
            converter = unit_conversion(
                log=log
            )
            try:
                ra = converter.ra_decimal_to_sexegesimal(
                    ra=ra,
                    delimiter=":"
                )
                dec = converter.dec_decimal_to_sexegesimal(
                    dec=dec,
                    delimiter=":"
                )
            except Exception, e:
                print e
                sys.exit(0)

            print ra, dec
        else:
            converter = unit_conversion(
                log=log
            )
            try:
                ra = converter.ra_sexegesimal_to_decimal(
                    ra=ra
                )
                dec = converter.dec_sexegesimal_to_decimal(
                    dec=dec
                )
            except Exception, e:
                print e
                sys.exit(0)
            print ra, dec

    if sep:
        from astrocalc.coords import separations
        calculator = separations(
            log=log,
            ra1=ra1,
            dec1=dec1,
            ra2=ra2,
            dec2=dec2,
        )
        angularSeparation, north, east = calculator.get()
        print """%(angularSeparation)s arcsec (%(north)s N, %(east)s E)""" % locals()

    if timeflip:
        try:
            inputMjd = float(datetime)
            if datetime[0] not in ["0", "1", "2"]:
                inputMjd = True
            else:
                inputMjd = False
        except:
            inputMjd = False
        from astrocalc.times import conversions
        converter = conversions(
            log=log
        )

        if inputMjd == False:
            try:
                mjd = converter.ut_datetime_to_mjd(utDatetime=datetime)
                print mjd
            except Exception, e:
                print e
        else:
            try:
                utDate = converter.mjd_to_ut_datetime(mjd=datetime)
                print utDate
            except Exception, e:
                print e

    if trans:
        # TRANSLATE COORDINATES ACROSS SKY
        from astrocalc.coords import translate
        newRa, newDec = translate(
            log=log,
            ra=ra,
            dec=dec,
            northArcsec=float(north),
            eastArcsec=float(east)
        ).get()
        from astrocalc.coords import unit_conversion
        converter = unit_conversion(
            log=log
        )
        ra = converter.ra_decimal_to_sexegesimal(
            ra=newRa,
            delimiter=":"
        )
        dec = converter.dec_decimal_to_sexegesimal(
            dec=newDec,
            delimiter=":"
        )

        print "%(newRa)s, %(newDec)s (%(ra)s, %(dec)s)" % locals()

    if now:
        from astrocalc.times import now
        mjd = now(
            log=log
        ).get_mjd()
        print mjd

    if dist and redshiftFlag:
        from astrocalc.distances import converter
        c = converter(log=log)
        if not hcFlag:
            hcFlag = 70.
        if not wmFlag:
            wmFlag = 0.3
        if not wvFlag:
            wvFlag = 0.7
        dists = c.redshift_to_distance(
            z=float(distVal),
            WM=float(wmFlag),
            WV=float(wvFlag),
            H0=float(hcFlag)
        )
        print "Distance Modulus: " + str(dists["dmod"]) + " mag"
        print "Luminousity Distance: " + str(dists["dl_mpc"]) + " Mpc"
        print "Angular Size Scale: " + str(dists["da_scale"]) + " kpc/arcsec"
        print "Angular Size Distance: " + str(dists["da_mpc"]) + " Mpc"
        print "Comoving Radial Distance: " + str(dists["dcmr_mpc"]) + " Mpc"

    if dist and mpcFlag:
        from astrocalc.distances import converter
        c = converter(log=log)
        z = c.distance_to_redshift(
            mpc=float(distVal)
        )
        print "z = %(z)s" % locals()

    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
1372139
def main():
    

    parser = make_parser()
    args = parser.parse_args()

    if not hasattr(args, 'action'):
        parser.print_help()
        exit(1)

    if args.action == 'sheet':
        from bernard.misc.sheet_sync import main as main_sheet
        main_sheet(args)
    elif args.action == 'run':
        from bernard.cli import main as main_run
        main_run()
    elif args.action == 'start_project':
        from bernard.misc.start_project import main as main_sp
        main_sp(args)
761316
def main():
    

    components_paths = []
    for path in (os.path.join(umbra.__path__[0], Constants.factory_components_directory),
                 os.path.join(umbra.__path__[0], Constants.factory_addons_components_directory)):
        os.path.exists(path) and components_paths.append(path)
    return umbra.engine.run(umbra.engine.Umbra,
                            umbra.engine.get_command_line_parameters_parser().parse_args(
                                [unicode(argument, Constants.default_codec, Constants.codec_error) for argument in
                                 sys.argv]),
                            components_paths,
                            ("factory.script_editor", "factory.preferences_manager", "factory.components_manager_ui"))
349585
def main(args=None):
    
    parser = ArgumentParser(
        prog='baseline',
        description=DESCRIPTION)

    parser.add_argument(
        'path', nargs='*',
        help='module or directory path')

    parser.add_argument(
        '--movepath', help='location to move script updates')

    parser.add_argument(
        '-w', '--walk', action='store_true',
        help='recursively walk directories')

    args = parser.parse_args(args)

    paths = args.path or ['.']

    paths = [path for pattern in paths for path in glob(pattern)]

    if args.walk:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            for root, _dirs, files in os.walk(dirpath):
                paths += (os.path.join(root, filename) for filename in files)
    else:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            paths += (os.path.join(dirpath, pth) for pth in os.listdir(dirpath))

    update_paths = [
        os.path.relpath(p) for p in paths if p.lower().endswith(UPDATE_EXT)]

    exitcode = 0

    if update_paths:
        script_paths = [pth[:-len(UPDATE_EXT)] + '.py' for pth in update_paths]

        print('Found updates for:')
        for path in script_paths:
            print('  ' + path)
        print()

        if not args.movepath:
            try:
                input('Hit [ENTER] to update, [Ctrl-C] to cancel ')
            except KeyboardInterrupt:
                print()
                print('Update canceled.')
                exitcode = 1
            else:
                print()

        if exitcode == 0:
            for script_path, update_path in zip(script_paths, update_paths):
                if args.movepath:
                    script_path = os.path.join(args.movepath, script_path)
                    if update_path.startswith('..'):
                        raise RuntimeError(
                            'destination outside of move path: ' + script_path)
                    script_dirpath = os.path.dirname(script_path)
                    if not os.path.isdir(script_dirpath):
                        os.makedirs(script_dirpath)
                with open(update_path) as update:
                    new_content = update.read()
                with open(script_path, 'w') as script:
                    script.write(new_content)
                os.remove(update_path)
                print(update_path + ' -> ' + script_path)

    return exitcode
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
291090
def main(argv=None):
    
    # Get command line arguments, validate them, and normalize them
    opts = cmdparse.parse_args(argv)
    assert validate_opts.validate(opts)
    opts = normalize_opts.normalize(opts)

    if opts.verbose:
        # Update client: print input and output directories
        messages.print_input_output(opts)

    file_paths = fileparse.get_file_list(opts)
    assert validate_files.validate(file_paths, opts)

    if opts.verbose and opts.is_dir:
        # Update client: print files that will be parsed
        messages.print_files(opts, file_paths)

    # For now, only using default GitHub Markdown for parsing
    # Collect tag/anchor combinations
    collector = make_github_markdown_collector(opts)
    anchors, duplicate_tags = collector.collect(file_paths)
    assert validate_anchors.validate(anchors, duplicate_tags, opts)

    # Write files using previously found AnchorHub tags and generated anchors
    writer = make_github_markdown_writer(opts)
    counter = writer.write(file_paths, anchors, opts)

    if opts.verbose:
        if opts.is_dir:
            # Update client: print files that had modifications
            messages.print_modified_files(opts, anchors)
        # Print summary statistics
        messages.print_summary_stats(counter)
531768
def main():
    
    # Define Parser object and add to Toil
    if mock_mode():
        usage_msg = 'You have the TOIL_SCRIPTS_MOCK_MODE environment variable set, so this pipeline ' \
                    'will run in mock mode. To disable mock mode, set TOIL_SCRIPTS_MOCK_MODE=0'
    else:
        usage_msg = None

    parser = argparse.ArgumentParser(usage=usage_msg)
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config', help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest', help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate', help='Generates a config and manifest in the current working directory.')
    # Run subparser                                                                                                              
    parser_run = subparsers.add_parser('run', help='Runs the ADAM/GATK pipeline')
    default_config = 'adam-gatk-mock.config' if mock_mode() else 'adam-gatk.config'
    default_manifest = 'adam-gatk-mock-manifest.csv' if mock_mode() else 'adam-gatk-manifest.csv'
    parser_run.add_argument('--config', default=default_config, type=str,
                            help='Path to the (filled in) config file, generated with "generate-config".')
    parser_run.add_argument('--manifest', default=default_manifest,
                            type=str, help='Path to the (filled in) manifest file, generated with "generate-manifest". '
                                           '\nDefault value: "%(default)s".')
    Job.Runner.addToilOptions(parser_run)
    args = parser.parse_args()

    cwd = os.getcwd()
    if args.command == 'generate-config' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_config), generate_config)
    if args.command == 'generate-manifest' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_manifest), generate_manifest)
    # Pipeline execution
    elif args.command == 'run':
        require(os.path.exists(args.config), '{} not found. Please run '
                                             'generate-config'.format(args.config))
        if not hasattr(args, 'sample'):
            require(os.path.exists(args.manifest), '{} not found and no samples provided. Please '
                                                   'run "generate-manifest"'.format(args.manifest))
        # Parse config
        parsed_config = {x.replace('-', '_'): y for x, y in yaml.load(open(args.config).read()).iteritems()}
        inputs = argparse.Namespace(**parsed_config)

        # Parse manifest file
        uuid_list = []
        with open(args.manifest) as f_manifest:
            for line in f_manifest:
                if not line.isspace() and not line.startswith('#'):
                    uuid_list.append(line.strip())

        inputs.sort = False
        if not inputs.dir_suffix:
            inputs.dir_suffix = ''
        if not inputs.s3_bucket:
            inputs.s3_bucket = ''

        if inputs.master_ip and inputs.num_nodes:
            raise ValueError("Exactly one of master_ip (%s) and num_nodes (%d) must be provided." %
                             (inputs.master_ip, inputs.num_nodes))

        if not hasattr(inputs, 'master_ip') and inputs.num_nodes <= 1:
            raise ValueError('num_nodes allocates one Spark/HDFS master and n-1 workers, and thus must be greater '
                             'than 1. %d was passed.' % inputs.num_nodes)

        if (inputs.pipeline_to_run != "adam" and
            inputs.pipeline_to_run != "gatk" and
            inputs.pipeline_to_run != "both"):
            raise ValueError("pipeline_to_run must be either 'adam', 'gatk', or 'both'. %s was passed." % inputs.pipeline_to_run)

        Job.Runner.startToil(Job.wrapJobFn(sample_loop, uuid_list, inputs), args)
1316337
def main(argv=None):
    ''' 

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

    return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv)
880354
def main(args=sys.argv):
    

    if len(args) < 2:
        return usage("Command expected")

    command = args[1]
    rest = args[2:]

    if "create".startswith(command):
        return cli_create(rest)
    elif "query".startswith(command):
        return cli_query(rest)
    elif "verify".startswith(command):
        return cli_verify(rest)
    else:
        return usage("Unknown command: %s" % command)
1227650
def main():
    
    version = 'Python Exist %s' % __version__
    arguments = docopt(__doc__, version=version)
    ExistCli(arguments)
178058
def run_main(args: argparse.Namespace, do_exit=True) -> None:
    
    if args.init:
        generate()
        return None  # exit after generate instead of starting to lint

    handler = CheckHandler(
        file=args.config_file, out_json=args.json, files=args.files)

    for style in get_stylers():
        handler.run_linter(style())

    for linter in get_linters():
        handler.run_linter(linter())

    for security in get_security():
        handler.run_linter(security())

    for tool in get_tools():
        tool = tool()

        # Only run pypi if everything else passed
        if tool.name == "pypi" and handler.status_code != 0:
            continue

        handler.run_linter(tool)

    if do_exit:
        handler.exit()
    return handler.status_code
659030
def main(argd=None):
    
    global DEBUG, debug

    # The argd parameter for main() is for testing purposes only.
    argd = argd or docopt(
        USAGESTR,
        version=VERSIONSTR,
        script=SCRIPT,
        # Example usage of colr_docopt colors.
        colors={
            'header': {'fore': 'yellow'},
            'script': {'fore': 'lightblue', 'style': 'bright'},
            'version': {'fore': 'lightblue'},
        }
    )

    DEBUG = argd['--debug']
    # Load real debug function if available.
    if DEBUG:
        load_debug_deps()
    else:
        debug = noop

    if argd['--auto-disable']:
        auto_disable()

    if argd['--names']:
        return list_names()
    elif argd['--translate']:
        # Just translate a simple code and exit.
        try:
            print('\n'.join(
                translate(
                    argd['CODE'] or read_stdin().split(),
                    rgb_mode=argd['--truecolor'],
                )
            ))
        except ValueError as ex:
            print_err('Translation error: {}'.format(ex))
            return 1
        return 0
    elif argd['--listcodes']:
        # List all escape codes found in some text and exit.
        return list_known_codes(
            argd['TEXT'] or read_stdin(),
            unique=argd['--unique'],
            rgb_mode=argd['--truecolor'],
        )

    txt = argd['TEXT'] or read_stdin()
    fd = sys.stderr if argd['--err'] else sys.stdout
    end = '' if argd['--newline'] else '\n'

    if argd['--stripcodes']:
        txt = justify(strip_codes(txt), argd)
        print(txt, file=fd, end=end)
        return 0

    clr = get_colr(txt, argd)

    # Center, ljust, rjust, or not.
    clr = justify(clr, argd)
    if clr:
        print(str(clr), file=fd, end=end)
        return 0
    # Error while building Colr.
    return 1
1195420
def main():
    """"""
    print("ERROR: Use the 'slcli' command instead.", file=sys.stderr)
    print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr)
    exit(-1)
133497
def main():
    
    pypitools.common.setup_main()
    config = pypitools.common.ConfigData()
    module_name = os.path.basename(os.getcwd())
    args = []
    if config.use_sudo:
        args.extend([
            'sudo',
            '-H',
        ])
    args.extend([
        '{}'.format(config.pip),
        'install',
        '--upgrade',
        '{module_name}'.format(module_name=module_name),
    ])
    if config.pip_quiet:
        args.extend([
            '--quiet',
        ])
    if config.install_in_user_folder:
        args.extend([
            '--user',
        ])
    pypitools.common.check_call_no_output(args)
    output = subprocess.check_output([
        '{}'.format(config.pip),
        'show',
        '{module_name}'.format(module_name=module_name),
    ]).decode()
    for line in output.split("\n"):
        if line.startswith("Version"):
            print(line)
612434
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="picaxe"
    )
    arguments, settings, log, dbConn = su.setup()

    startTime = times.get_now_sql_datetime()

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

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/picaxe/picaxe.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

    if auth:
        from picaxe import picaxe
        client = picaxe(
            log=log,
            settings=settings,
            pathToSettingsFile=pathToSettingsFile
        )
        client.authenticate()

    if md:
        from picaxe import picaxe
        Flickr = picaxe(
            log=log,
            settings=settings
        )
        if not width:
            width = "original"
        mdLink = Flickr.md(
            url=urlOrPhotoid,
            # [75, 100, 150, 240, 320, 500, 640, 800, 1024, 1600, 2048]
            width=width
        )
        print mdLink

    if albums:
        from picaxe import picaxe
        flickr = picaxe(
            log=log,
            settings=settings
        )
        albumList = flickr.list_album_titles()
        for a in albumList:
            print a

    if upload:
        from picaxe import picaxe
        flickr = picaxe(
            log=log,
            settings=settings
        )

        imageType = "photo"
        if screenGrabFlag:
            imageType = "screengrab"
        elif imageFlag:
            imageType = "image"

        album = "inbox"
        if albumFlag:
            album = albumFlag

        photoid = flickr.upload(
            imagePath=imagePath,
            title=titleFlag,
            private=publicFlag,
            tags=tagsFlag,
            description=descFlag,
            imageType=imageType,  # image|screengrab|photo
            album=albumFlag,
            openInBrowser=openFlag
        )
        print photoid

    if grab:

        # for k, v in locals().iteritems():
        #     print k, v
        # return
        try:
            os.remove("/tmp/screengrab.png")
        except:
            pass

        if delayFlag:

            time.sleep(int(delayFlag))

        from subprocess import Popen, PIPE, STDOUT
        cmd = """screencapture -i /tmp/screengrab.png""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        stdout, stderr = p.communicate()
        log.debug('output: %(stdout)s' % locals())

        exists = os.path.exists("/tmp/screengrab.png")
        if exists:
            from picaxe import picaxe
            flickr = picaxe(
                log=log,
                settings=settings
            )

            if not albumFlag:
                albumFlag = "screengrabs"

            photoid = flickr.upload(
                imagePath="/tmp/screengrab.png",
                title=titleFlag,
                private=publicFlag,
                tags=tagsFlag,
                description=descFlag,
                imageType="screengrab",  # image|screengrab|photo
                album=albumFlag,
                openInBrowser=openFlag
            )
            mdLink = flickr.md(
                url=photoid,
                # [75, 100, 150, 240, 320, 500, 640, 800, 1024, 1600, 2048]
                width="original"
            )
            print mdLink

    # 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
21059
def main():
    
    plugins = DefaultPluginManager()
    plugins.load_plugins()

    parser, _ = create_argparser()
    # add the updater protocol options to the CLI:
    for kls in updater_classes():
        kls.register_arguments(parser)

    for kls in detector_classes():
        kls.register_arguments(parser)

    # add the plugin options to the CLI:
    from os import environ
    plugins.options(parser, environ)

    args = parser.parse_args()

    if args.debug:
        args.verbose_count = 5  # some high number

    log_level = max(int(logging.WARNING / 10) - args.verbose_count, 0) * 10
    # print(log_level)
    logging.basicConfig(level=log_level, format="%(levelname)s %(message)s")
    # logging.debug("args %r", args)

    if args.version:
        from . import __version__
        print("dyndnsc %s" % __version__)  # noqa
        return 0

    # silence 'requests' logging
    requests_log = logging.getLogger("requests")
    requests_log.setLevel(logging.WARNING)

    logging.debug(parser)
    cfg = get_configuration(args.config)

    if args.listpresets:
        list_presets(cfg)
        return 0

    if args.config:
        collected_configs = collect_config(cfg)
    else:
        parsed_args = parse_cmdline_args(args, updater_classes().union(detector_classes()))
        logging.debug("parsed_args %r", parsed_args)

        collected_configs = {
            "cmdline": {
                "interval": int(args.sleeptime)
            }
        }
        collected_configs["cmdline"].update(parsed_args)

    plugins.configure(args)
    plugins.initialize()

    logging.debug("collected_configs: %r", collected_configs)
    dyndnsclients = []
    for thisconfig in collected_configs:
        logging.debug("Initializing client for '%s'", thisconfig)
        # done with options, bring on the dancing girls
        dyndnsclient = getDynDnsClientForConfig(
            collected_configs[thisconfig], plugins=plugins)
        if dyndnsclient is None:
            return 1
        # do an initial synchronization, before going into endless loop:
        dyndnsclient.sync()
        dyndnsclients.append(dyndnsclient)

    run_forever_callable = partial(run_forever, dyndnsclients)

    if args.daemon:
        import daemonocle
        daemon = daemonocle.Daemon(worker=run_forever_callable)
        daemon.do_action("start")
        args.loop = True

    if args.loop:
        run_forever_callable()

    return 0
243897
def main(argv=None):
    
    from vsgen import VSGSuite
    from vsgen import VSGLogger

    # Special case to use the sys.argv when main called without a list.
    if argv is None:
        argv = sys.argv

    # Initialize the application logger
    pylogger = VSGLogger()

    # Construct a command line parser and parse the command line
    args = VSGSuite.make_parser(description='Executes the vsgen package as an application.').parse_args(argv[1:])
    for s in VSGSuite.from_args(**vars(args)):
        s.write(False)
    return 0