Handles the arguments defined by :meth:`~make_common_parser`

    :param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
    :return: An :class:`~InitFileHandler` object
    :raise IOError: Initial or run script not found
2297
def handle_common_arguments(parsed_args):
    
    # Setup the logger
    logging.basicConfig(
        level=logging.DEBUG if parsed_args.verbose else logging.WARNING
    )

    # Framework properties dictionary
    props = {}

    # Read the initial configuration script
    init = InitFileHandler()
    if not parsed_args.init_empty:
        if not parsed_args.init_conf_exclusive:
            # Load default configuration
            init.load()

        # Load the given configuration file
        conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf
        if conf_file:
            init.load(conf_file)

        # Normalize configuration
        init.normalize()

        # Set initial framework properties
        props.update(init.properties)

    # Compute framework properties
    for prop_def in parsed_args.properties or []:
        key, value = prop_def.split("=", 1)
        props[key] = value

    # Check initial run script(s)
    if parsed_args.init_script:
        path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script)
        if not path:
            raise IOError(
                "Initial script file not found: {0}".format(
                    parsed_args.init_script
                )
            )

    if parsed_args.run_script:
        # Find the file
        path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script)
        if not path:
            raise IOError(
                "Script file not found: {0}".format(parsed_args.run_script)
            )

    # Update the stored configuration
    init.properties.update(props)
    return init
1219109
def parse_args(self, args=None, namespace=None):
        
        self._expand_prefixed_files(args)
        return super(CLICommandParser, self).parse_args(args)
1177879
def exec_argparse_funckw(func, globals_=None, defaults={}, **kwargs):
    
    import utool as ut
    funckw = ut.get_func_kwargs(func)
    funckw.update(defaults)
    parsekw = ut.argparse_dict(funckw, **kwargs)
    if globals_:
        globals_.update(parsekw)
    return parsekw
566603
def genargs() -> ArgumentParser:
    
    parser = ArgumentParser()
    parser.add_argument("infile", help="Input JSG specification")
    parser.add_argument("-o", "--outfile", help="Output python file (Default: {infile}.py)")
    parser.add_argument("-e", "--evaluate", help="Evaluate resulting python file as a test", action="store_true")
    parser.add_argument("-v", "--verbose", help="Verbose output", action="store_true")
    return parser
934582
def _parse_arguments():
    
    parser = argparse.ArgumentParser(
        description='eg provides examples of common command usage.'
    )

    parser.add_argument(
        '-v',
        '--version',
        action='store_true',
        help='Display version information about eg'
    )

    parser.add_argument(
        '-f',
        '--config-file',
        help='Path to the .egrc file, if it is not in the default location.'
    )

    parser.add_argument(
        '-e',
        '--edit',
        action='store_true',
        help="""Edit the custom examples for the given command. If editor-cmd
        is not set in your .egrc and $VISUAL and $EDITOR are not set, prints a
        message and does nothing."""
    )

    parser.add_argument(
        '--examples-dir',
        help='The location to the examples/ dir that ships with eg'
    )

    parser.add_argument(
        '-c',
        '--custom-dir',
        help='Path to a directory containing user-defined examples.'
    )

    parser.add_argument(
        '-p',
        '--pager-cmd',
        help='String literal that will be invoked to page output.'
    )

    parser.add_argument(
        '-l',
        '--list',
        action='store_true',
        help='Show all the programs with eg entries.'
    )

    parser.add_argument(
        '--color',
        action='store_true',
        dest='use_color',
        default=None,
        help='Colorize output.'
    )

    parser.add_argument(
        '-s',
        '--squeeze',
        action='store_true',
        default=None,
        help='Show fewer blank lines in output.'
    )

    parser.add_argument(
        '--no-color',
        action='store_false',
        dest='use_color',
        help='Do not colorize output.'
    )

    parser.add_argument(
        'program',
        nargs='?',
        help='The program for which to display examples.'
    )

    args = parser.parse_args()

    if len(sys.argv) < 2:
        # Too few arguments. We can't specify this using argparse alone, so we
        # have to manually check.
        parser.print_help()
        parser.exit()
    elif not args.version and not args.list and not args.program:
        parser.error(_MSG_BAD_ARGS)
    else:
        return args
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
304987
def parse_args():
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--lint',
                        help='Path to the ADT lint tool. If not specified it assumes lint tool is in your path',
                        default='lint')
    parser.add_argument('--app',
                        help='Path to the Android app. If not specifies it assumes current directory is your Android '
                             'app directory',
                        default='.')
    parser.add_argument('--xml',
                        help='Path to the lint result. If not specifies linting will be done by the script',
                        default=None)
    parser.add_argument('--ignore-layouts',
                        help='Should ignore layouts',
                        action='store_true')
    args = parser.parse_args()
    return args.lint, args.app, args.xml, args.ignore_layouts
540121
def parse(self, *args, **kwargs):  # pylint: disable=unused-argument
        
        # pylint: disable=W0703
        cmd = args[0]
        resp = args[1]
        if cmd in self.parsers:
            try:
                return self.parsers[cmd](resp)
            except Exception as err:
                print(err)
        return {}
194133
def init_parsecmdline(argv=[]):
    
    # main argument parser
    parser = argparse.ArgumentParser(prog=PKG_NAME)

    # --version
    parser.add_argument('--version', action='version', version=version)

    # -c, --config <file_name>
    parser.add_argument("-c", "--config",
                        action="store",
                        dest="config_file", default=config.CONF_DEFAULT_FILE,
                        help="specify configuration file to use")

    # --dry-run
    parser.add_argument("-d", "--dry-run",
                        action="store_true",  dest="dry_run", default=False,
                        help="don't actually do anything")

    # --quiet
    parser.add_argument("-q", "--quiet",
                        action="store_true",  dest="log_quiet", default=False,
                        help="quiet output")

    # --ll <level>
    # logging level
    parser.add_argument("--ll", "--log-level",
                        action="store", type=int,
                        dest="log_lvl", default=log.LOG_LVL_DEFAULT,
                        help="set logging level")

    # -l, --log-file
    parser.add_argument("-l", "--log-file",
                        action="store",
                        dest="log_file", default=log.LOG_FILE_DEFAULT,
                        help="set log file")

    # Absorb the options
    options = parser.parse_args(argv)

    # Set whether we are going to perform a dry run
    global _opt
    _opt["dry_run"] = options.dry_run

    # Initiate the log level
    log.init(threshold_lvl=options.log_lvl,
             quiet_stdout=options.log_quiet, log_file=options.log_file)

    #
    # Print the splash
    #
    _splash()

    # Merge configuration with a JSON file
    config_file = os.path.abspath(options.config_file)
    log.msg("Attempting to use configuration file '{config_file}'"
            .format(config_file=config_file))
    try:
        config.set_from_file(config_file)
    except FileNotFoundError:
        raise FileNotFoundError("Configuration file '{config_file}' not found!"
                                .format(config_file=config_file))
659368
def init_dataset_prepare_args(self, parser):
        ''' '''
        parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
                            help='the path to the configuration file to use -- ./config.yaml by default')
        parser.add_argument('-c', '--corpus-name', help='the name of the corpus to process')
        parser.add_argument('-n', '--dataset-name', help='the name to assign the newly processed dataset')
1267396
def add_arguments(parser):
    
    parser.description = 'Examples:\n' \
                         'python -m etk html_content_extractor /tmp/input.html\n' \
                         'cat /tmp/input.html | python -m etk html_content_extractor'
    parser.add_argument('input_file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
416593
def handle_args_and_set_context(args):
  
  parser = argparse.ArgumentParser()
  parser.add_argument("env", help="environment")
  parser.add_argument("path_to_template", help="path to the config template to process")
  parser.add_argument("--no_params", help="disable loading values from params file", action="store_true", default=False)
  parser.add_argument("--verbose", help="Output extra info", action="store_true", default=False)
  parser.add_argument("--lint", help="Test configs for valid JSON/YAML syntax", action="store_true", default=False)
  parser.add_argument("--silent", help="Suppress output of rendered template", action="store_true", default=False)
  parsed = vars(parser.parse_args(args))
  path_to_template = abspath(parsed["path_to_template"])
  service = path_to_template.split('/')[-3]

  return Context(
      get_account_alias(parsed["env"]),
      EFConfig.DEFAULT_REGION,
      parsed["env"],
      service,
      path_to_template,
      parsed["no_params"],
      parsed["verbose"],
      parsed["lint"],
      parsed["silent"]
  )
1175269
def parse_args(self, args=None, namespace=None):
        
        if not namespace:  # use the new Namespace class for handling _config
            namespace = Namespace(self)
        namespace = super(ArgumentParser, self).parse_args(args, namespace)
        if len(self._reparse_args['pos']) > 0 or \
           len(self._reparse_args['opt']) > 0 or \
           len(self._reparse_args['sub']) > 0:
            args = self._reset_args()
            namespace = super(ArgumentParser, self).parse_args(args, namespace)
        # process "-hh..." here, after having parsed the arguments
        help_level = getattr(namespace, "help", 0)
        if help_level > 0:
            self.print_help()
            self.print_extended_help(help_level)
            self.exit()
        return namespace
1081743
def init_handler(args):
    
    try:
        initialize_repository(pathlib.Path.cwd())
    except ValueError as exc:
        print(exc, file=sys.stderr)
        return ExitCode.DATAERR

    return ExitCode.OK
620502
def create_argparser():
    
    parser = argparse.ArgumentParser()
    arg_defaults = {
        "daemon": False,
        "loop": False,
        "listpresets": False,
        "config": None,
        "debug": False,
        "sleeptime": 300,
        "version": False,
        "verbose_count": 0
    }

    # add generic client options to the CLI:
    parser.add_argument("-c", "--config", dest="config",
                        help="config file", default=arg_defaults["config"])
    parser.add_argument("--list-presets", dest="listpresets",
                        help="list all available presets",
                        action="store_true", default=arg_defaults["listpresets"])
    parser.add_argument("-d", "--daemon", dest="daemon",
                        help="go into daemon mode (implies --loop)",
                        action="store_true", default=arg_defaults["daemon"])
    parser.add_argument("--debug", dest="debug",
                        help="increase logging level to DEBUG (DEPRECATED, please use -vvv)",
                        action="store_true", default=arg_defaults["debug"])
    parser.add_argument("--loop", dest="loop",
                        help="loop forever (default is to update once)",
                        action="store_true", default=arg_defaults["loop"])
    parser.add_argument("--sleeptime", dest="sleeptime",
                        help="how long to sleep between checks in seconds",
                        default=arg_defaults["sleeptime"])
    parser.add_argument("--version", dest="version",
                        help="show version and exit",
                        action="store_true", default=arg_defaults["version"])
    parser.add_argument("-v", "--verbose", dest="verbose_count",
                        action="count", default=arg_defaults["verbose_count"],
                        help="increases log verbosity for each occurrence")

    return parser, arg_defaults
936512
def handle_parser():
    
    parser = argparse.ArgumentParser(description="Runs the pymoresane deconvolution algorithm with the specified "
                                                 "arguments. In the event that non-critical parameters are missing, "
                                                 "the defaults will be used.",
                                                  formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("dirty", help="File name and location of the input dirty map .fits file.")

    parser.add_argument("psf", help="File name and location input psf .fits file.")

    parser.add_argument("outputname", help="File name and location of the output model and residual .fits files.",
                        nargs='?', default=None)

    parser.add_argument("-sr", "--singlerun", help="Specify whether pymoresane is to be run in scale-by-scale mode or "
                                                   "in single-run mode. Scale-by-scale is usually the better choice."
                                                   , action="store_true")

    parser.add_argument("-sbr", "--subregion", help="Specify pixel width of the central region of the dirty .fits "
                                                   "which is to be deconvolved.", default=None, type=int)

    parser.add_argument("-sc", "--scalecount", help="Specify the maximum number of wavelet scales which the algorithm "
                                                    "is to consider. Only applies in single-run mode. For "
                                                    "scale-by-scale mode, use --startscale and --stopscale"
                                                    , default=None,type=int)

    parser.add_argument("-sts", "--startscale", help="Specify first scale to consider in the scale-by-scale case. "
                                                     "Should be 1 in almost all cases.", default=1, type=int)

    parser.add_argument("-sps", "--stopscale", help="Specify last scale to consider in the scale-by-scale case. "
                                                    "Can be safely omitted if all scales are to be considered."
                                                    , default=20, type=int)

    parser.add_argument("-sl", "--sigmalevel", help="Specify the sigma level at which the thresholding of the wavelet "
                                                    "coefficients is to be performed. May be used to reduce false "
                                                    "detections.", default=4, type=float)

    parser.add_argument("-lg", "--loopgain", help="Specify the loop gain for the deconvolution step."
                                                  , default=0.2, type=float)

    parser.add_argument("-tol", "--tolerance", help="Specify the percentage of the maximum wavelet coefficient which "
                                                    "is to be used as a threshold for significance at each iteration."
                                                    , default=0.75, type=float)

    parser.add_argument("-ac", "--accuracy", help="Specify the relative change in the STD of the residual that is "
                                                  "considered sufficient as a stopping criteria."
                                                  , default=1e-6, type=float)

    parser.add_argument("-malm", "--majorloopmiter", help="Specify the maximum number of major loop iterations."
                                                          , default=100, type=int)

    parser.add_argument("-milm", "--minorloopmiter", help="Specify the maximum number of minor loop iterations."
                                                          , default=50, type=int)

    parser.add_argument("-aog", "--allongpu", help="Specify whether as much code as possible is to be executed on the "
                                                   "gpu. Overrides the behaviour of all other gpu options"
                                                   , action='store_true')

    parser.add_argument("-dm", "--decommode", help="Specify whether wavelet decompositions are to performed using a "
                                                   "single CPU core, multiple CPU cores or the GPU."
                                                   , default="ser", choices=["ser","mp","gpu"])

    parser.add_argument("-cc", "--corecount", help="Specify the number of CPU cores to be used in the event that "
                                                   "multiprocessing is enabled. This might not improve performance."
                                                   , default=1, type=int)

    parser.add_argument("-cd", "--convdevice", help="Specify whether convolutions are to performed using the CPU or "
                                                    "the GPU.", default="cpu", choices=["cpu","gpu"])

    parser.add_argument("-cm", "--convmode", help="Specify convolution is to be circular or linear."
                                                  , default="circular", choices=["circular","linear"])

    parser.add_argument("-em", "--extractionmode", help="Specify whether source extraction is to be performed "
                                                        "using the CPU or the GPU."
                                                        , default="cpu", choices=["cpu","gpu"])

    parser.add_argument("-ep", "--enforcepositivity", help="Specify whether or not the model is constrained to be "
                                                           "strictly positive. Will massively improve the model in "
                                                           "simulated cases, but may cause problems with real data."
                                                           , action="store_true")

    parser.add_argument("-es", "--edgesuppression", help="Specify whether or not the edge-corrupted wavelets are to "
                                                         "be suppressed. Will decrease sensitivity along data edges."
                                                         , action="store_true")

    parser.add_argument("-eo", "--edgeoffset", help="Specify an additional offset along the edges. May reduce false "
                                                    "detections caused by convolution artifacts."
                                                    , default=0, type=int)

    parser.add_argument("-ll", "--loglevel", help="Specify logging level.", default="INFO"
                                                  , choices=["DEBUG","INFO", "WARNING", "ERROR","CRITICAL"])

    parser.add_argument("-m", "--mask", help="File name and location of the input .fits mask.", default=None)

    parser.add_argument("-ft", "--fluxthreshold", help="Flux threshold level for shallow deconvolution.", default=0,
                        type=float)

    parser.add_argument("-rn", "--residualname", help="Specific residual image name.", default=None)

    parser.add_argument("-mn", "--modelname", help="Specific model image name.", default=None)

    parser.add_argument("-rsn", "--restoredname", help="Specific restored image name.", default=None)

    parser.add_argument("-nc", "--negcomp", help="Specify whether "
                                                 "anticorrelations are to be "
                                                 "used in the source "
                                                 "extraction step."
                                                 , action='store_true')

    parser.add_argument("-ee", "--edgeexcl", help="Number of pixels to "
                                                  "exclude from the edges "
                                                  "when estimating the noise"
                                                  ".", type=int, default=0)

    parser.add_argument("-ie", "--intexcl", help="Number of pixels to "
                                                  "exclude from the center "
                                                  "when estimating the noise"
                                                  ".", type=int, default=0)

    return parser.parse_args()
1287516
def main(args=None):
    
    import argparse
    from textwrap import dedent
    parser = argparse.ArgumentParser(
        formatter_class=type('EPCHelpFormatter',
                             (argparse.ArgumentDefaultsHelpFormatter,
                              argparse.RawDescriptionHelpFormatter),
                             {}),
        description=dedent(main.__doc__))
    parser.add_argument(
        'module', help='Serve python functions in this module.')
    parser.add_argument(
        '--address', default='localhost',
        help='server address')
    parser.add_argument(
        '--port', default=0, type=int,
        help='server port. 0 means to pick up random port.')
    parser.add_argument(
        '--allow-dotted-names', default=False, action='store_true')
    parser.add_argument(
        '--pdb', dest='debugger', const='pdb', action='store_const',
        help='start pdb when error occurs.')
    parser.add_argument(
        '--ipdb', dest='debugger', const='ipdb', action='store_const',
        help='start ipdb when error occurs.')
    parser.add_argument(
        '--log-traceback', action='store_true', default=False)
    ns = parser.parse_args(args)

    server = EPCServer((ns.address, ns.port),
                       debugger=ns.debugger,
                       log_traceback=ns.log_traceback)
    server.register_instance(
        __import__(ns.module),
        allow_dotted_names=ns.allow_dotted_names)
    server.print_port()
    server.serve_forever()