Create a command line argument parser

        Add a few default flags, such as --version
        for displaying the program version when invoked
775644
def new_parser(self):
        

        parser = argparse.ArgumentParser(description=self.description)
        parser.add_argument(
            '--version', help='show version and exit',
            default=False, action='store_true')
        parser.add_argument(
            '--debug', help='enable debugging',
            default=False, action='store_true')
        return parser
950012
def build_parser(self):
        """"""
        # Create top level argument parser.
        parser = argparse.ArgumentParser(
            description='PyOCD debug tools for Arm Cortex devices')
        subparsers = parser.add_subparsers(title="subcommands", metavar="", dest='cmd')
        
        parser.add_argument('-V', '--version', action='version', version=__version__)
        parser.add_argument('--help-options', action='store_true',
            help="Display available session options.")
        
        # Define logging related options.
        loggingOptions = argparse.ArgumentParser(description='logging', add_help=False)
        loggingOptions.add_argument('-v', '--verbose', action='count', default=0,
            help="More logging. Can be specified multiple times.")
        loggingOptions.add_argument('-q', '--quiet', action='count', default=0,
            help="Less logging. Can be specified multiple times.")
        
        # Define common options for all subcommands, excluding --verbose and --quiet.
        commonOptionsNoLogging = argparse.ArgumentParser(description='common', add_help=False)
        commonOptionsNoLogging.add_argument('-j', '--dir', metavar="PATH", dest="project_dir", default=os.getcwd(),
            help="Set the project directory. Defaults to the directory where pyocd was run.")
        commonOptionsNoLogging.add_argument('--config', metavar="PATH",
            help="Specify YAML configuration file. Default is pyocd.yaml or pyocd.yml.")
        commonOptionsNoLogging.add_argument("--no-config", action="store_true",
            help="Do not use a configuration file.")
        commonOptionsNoLogging.add_argument('--script', metavar="PATH",
            help="Use the specified user script. Defaults to pyocd_user.py.")
        commonOptionsNoLogging.add_argument('-O', action='append', dest='options', metavar="OPTION=VALUE",
            help="Set named option.")
        commonOptionsNoLogging.add_argument("-da", "--daparg", dest="daparg", nargs='+',
            help="Send setting to DAPAccess layer.")
        commonOptionsNoLogging.add_argument("--pack", metavar="PATH", action="append",
            help="Path to a CMSIS Device Family Pack.")
        
        # Define common options for all subcommands with --verbose and --quiet.
        commonOptions = argparse.ArgumentParser(description='common',
            parents=[loggingOptions, commonOptionsNoLogging], add_help=False)
        
        # Common connection related options.
        connectOptions = argparse.ArgumentParser(description='common', add_help=False)
        connectOptions.add_argument("-u", "--uid", dest="unique_id",
            help="Choose a probe by its unique ID or a substring thereof.")
        connectOptions.add_argument("-b", "--board", dest="board_override", metavar="BOARD",
            help="Set the board type (not yet implemented).")
        connectOptions.add_argument("-t", "--target", dest="target_override", metavar="TARGET",
            help="Set the target type.")
        connectOptions.add_argument("-f", "--frequency", dest="frequency", default=1000000, type=convert_frequency,
            help="SWD/JTAG clock frequency in Hz, with optional k/K or m/M suffix for kHz or MHz.")
        connectOptions.add_argument("-W", "--no-wait", action="store_true",
            help="Do not wait for a probe to be connected if none are available.")

        # Create *commander* subcommand parser.
        commandOptions = argparse.ArgumentParser(description='command', add_help=False)
        commandOptions.add_argument("-H", "--halt", action="store_true",
            help="Halt core upon connect.")
        commandOptions.add_argument("-N", "--no-init", action="store_true",
            help="Do not init debug system.")
        commandOptions.add_argument("--elf", metavar="PATH",
            help="Optionally specify ELF file being debugged.")
        commandOptions.add_argument("-c", "--command", dest="commands", metavar="CMD", action='append', nargs='+',
            help="Run commands.")
        subparsers.add_parser('commander', parents=[commonOptions, connectOptions, commandOptions],
            help="Interactive command console.")
        subparsers.add_parser('cmd', parents=[commonOptions, connectOptions, commandOptions],
            help="Alias for 'commander'.")

        # Create *erase* subcommand parser.
        eraseParser = subparsers.add_parser('erase', parents=[commonOptions, connectOptions],
            help="Erase entire device flash or specified sectors.",
            epilog="If no position arguments are listed, then no action will be taken unless the --chip or "
            "--mass-erase options are provided. Otherwise, the positional arguments should be the addresses of flash "
            "sectors or address ranges. The end address of a range is exclusive, meaning that it will not be "
            "erased. Thus, you should specify the address of the sector after the last one "
            "to be erased. If a '+' is used instead of '-' in a range, this indicates that the "
            "second value is a length rather than end address. "
            "Examples: 0x1000 (erase single sector starting at 0x1000) "
            "0x800-0x2000 (erase sectors starting at 0x800 up to but not including 0x2000) "
            "0+8192 (erase 8 kB starting at address 0)")
        eraseParser.add_argument("-c", "--chip", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.CHIP,
            help="Perform a chip erase.")
        eraseParser.add_argument("-s", "--sector", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.SECTOR,
            help="Erase the sectors listed as positional arguments.")
        eraseParser.add_argument("--mass-erase", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.MASS,
            help="Perform a mass erase. On some devices this is different than a chip erase.")
        eraseParser.add_argument("addresses", metavar="<sector-address>", action='append', nargs='*',
            help="List of sector addresses or ranges to erase.")

        # Create *flash* subcommand parser.
        flashParser = subparsers.add_parser('flash', parents=[commonOptions, connectOptions],
            help="Program an image to device flash.")
        flashParser.add_argument("-e", "--erase", choices=ERASE_OPTIONS.keys(), default='sector',
            help="Choose flash erase method. Default is sector.")
        flashParser.add_argument("-a", "--base-address", metavar="ADDR", type=int_base_0,
            help="Base address used for the address where to flash a binary. Defaults to start of flash.")
        flashParser.add_argument("--trust-crc", action="store_true",
            help="Use only the CRC of each page to determine if it already has the same data.")
        flashParser.add_argument("--format", choices=("bin", "hex", "elf"),
            help="File format. Default is to use the file's extension.")
        flashParser.add_argument("--skip", metavar="BYTES", default=0, type=int_base_0,
            help="Skip programming the first N bytes. This can only be used with binary files.")
        flashParser.add_argument("file", metavar="PATH",
            help="File to program into flash.")
        
        # Create *gdbserver* subcommand parser.
        gdbserverOptions = argparse.ArgumentParser(description='gdbserver', add_help=False)
        gdbserverOptions.add_argument("-p", "--port", dest="port_number", type=int, default=3333,
            help="Set the port number that GDB server will open (default 3333).")
        gdbserverOptions.add_argument("-T", "--telnet-port", dest="telnet_port", type=int, default=4444,
            help="Specify the telnet port for semihosting (default 4444).")
        gdbserverOptions.add_argument("--allow-remote", dest="serve_local_only", default=True, action="store_false",
            help="Allow remote TCP/IP connections (default is no).")
        gdbserverOptions.add_argument("--persist", dest="persist", default=False, action="store_true",
            help="Keep GDB server running even after remote has detached.")
        gdbserverOptions.add_argument("--elf", metavar="PATH",
            help="Optionally specify ELF file being debugged.")
        gdbserverOptions.add_argument("-e", "--erase", choices=ERASE_OPTIONS.keys(), default='sector',
            help="Choose flash erase method. Default is sector.")
        gdbserverOptions.add_argument("--trust-crc", action="store_true",
            help="Use only the CRC of each page to determine if it already has the same data.")
        gdbserverOptions.add_argument("-C", "--vector-catch", default='h',
            help="Enable vector catch sources, one letter per enabled source in any order, or 'all' "
                "or 'none'. (h=hard fault, b=bus fault, m=mem fault, i=irq err, s=state err, "
                "c=check err, p=nocp, r=reset, a=all, n=none). Default is hard fault.")
        gdbserverOptions.add_argument("-S", "--semihosting", dest="enable_semihosting", action="store_true",
            help="Enable semihosting.")
        gdbserverOptions.add_argument("--step-into-interrupts", dest="step_into_interrupt", default=False, action="store_true",
            help="Allow single stepping to step into interrupts.")
        gdbserverOptions.add_argument("-c", "--command", dest="commands", metavar="CMD", action='append', nargs='+',
            help="Run command (OpenOCD compatibility).")
        subparsers.add_parser('gdbserver', parents=[commonOptions, connectOptions, gdbserverOptions],
            help="Run the gdb remote server(s).")
        subparsers.add_parser('gdb', parents=[commonOptions, connectOptions, gdbserverOptions],
            help="Alias for 'gdbserver'.")

        # Create *json* subcommand parser.
        #
        # The json subcommand does not support --verbose or --quiet since all logging is disabled.
        jsonParser = subparsers.add_parser('json', parents=[commonOptionsNoLogging],
            help="Output information as JSON.")
        group = jsonParser.add_mutually_exclusive_group()
        group.add_argument('-p', '--probes', action='store_true',
            help="List available probes.")
        group.add_argument('-t', '--targets', action='store_true',
            help="List all known targets.")
        group.add_argument('-b', '--boards', action='store_true',
            help="List all known boards.")
        jsonParser.set_defaults(verbose=0, quiet=0)

        # Create *list* subcommand parser.
        listParser = subparsers.add_parser('list', parents=[commonOptions],
            help="List information about probes, targets, or boards.")
        group = listParser.add_mutually_exclusive_group()
        group.add_argument('-p', '--probes', action='store_true',
            help="List available probes.")
        group.add_argument('-t', '--targets', action='store_true',
            help="List all known targets.")
        group.add_argument('-b', '--boards', action='store_true',
            help="List all known boards.")
        listParser.add_argument('-n', '--name',
            help="Restrict listing to items matching the given name.")

        # Create *pack* subcommand parser.
        packParser = subparsers.add_parser('pack', parents=[loggingOptions],
            help="Manage CMSIS-Packs for target support.")
        packParser.add_argument("-c", "--clean", action='store_true',
            help="Erase all stored pack information.")
        packParser.add_argument("-u", "--update", action='store_true',
            help="Update the pack index.")
        packParser.add_argument("-s", "--show", action='store_true',
            help="Show the list of installed packs.")
        packParser.add_argument("-f", "--find", dest="find_devices", metavar="GLOB", action='append',
            help="Look up a device part number in the index using a glob pattern. The pattern is "
                "suffixed with '*'. Can be specified multiple times.")
        packParser.add_argument("-i", "--install", dest="install_devices", metavar="GLOB", action='append',
            help="Download and install pack(s) to support targets matching the glob pattern. "
                "The pattern is suffixed with '*'. Can be specified multiple times.")
        packParser.add_argument("-n", "--no-download", action='store_true',
            help="Just list the pack(s) that would be downloaded, don't actually download anything.")
        
        self._parser = parser
        return parser
1332181
def parse_args(self, flags, namespace):
    """"""
    flag_value_map = self._create_flag_value_map(flags)

    mutex_map = defaultdict(list)
    for args, kwargs in self._unnormalized_option_registrations_iter():
      self._validate(args, kwargs)
      dest = self.parse_dest(*args, **kwargs)

      # Compute the values provided on the command line for this option.  Note that there may be
      # multiple values, for any combination of the following reasons:
      #   - The user used the same flag multiple times.
      #   - The user specified a boolean flag (--foo) and its inverse (--no-foo).
      #   - The option has multiple names, and the user used more than one of them.
      #
      # We also check if the option is deprecated, but we only do so if the option is explicitly
      # specified as a command-line flag, so we don't spam users with deprecated option values
      # specified in config, which isn't something they control.
      implicit_value = kwargs.get('implicit_value')
      if implicit_value is None and kwargs.get('type') == bool:
        implicit_value = True  # Allows --foo to mean --foo=true.

      flag_vals = []

      def add_flag_val(v):
        if v is None:
          if implicit_value is None:
            raise ParseError('Missing value for command line flag {} in {}'.format(
              arg, self._scope_str()))
          else:
            flag_vals.append(implicit_value)
        else:
          flag_vals.append(v)

      for arg in args:
        # If the user specified --no-foo on the cmd line, treat it as if the user specified
        # --foo, but with the inverse value.
        if kwargs.get('type') == bool:
          inverse_arg = self._inverse_arg(arg)
          if inverse_arg in flag_value_map:
            flag_value_map[arg] = [self._invert(v) for v in flag_value_map[inverse_arg]]
            implicit_value = self._invert(implicit_value)
            del flag_value_map[inverse_arg]

        if arg in flag_value_map:
          for v in flag_value_map[arg]:
            add_flag_val(v)
          del flag_value_map[arg]

      # Get the value for this option, falling back to defaults as needed.
      try:
        val = self._compute_value(dest, kwargs, flag_vals)
      except ParseError as e:
        # Reraise a new exception with context on the option being processed at the time of error.
        # Note that other exception types can be raised here that are caught by ParseError (e.g.
        # BooleanConversionError), hence we reference the original exception type as type(e).
        raise type(e)(
          'Error computing value for {} in {} (may also be from PANTS_* environment variables).'
          '\nCaused by:\n{}'.format(', '.join(args), self._scope_str(), traceback.format_exc())
        )

      # If the option is explicitly given, check deprecation and mutual exclusion.
      if val.rank > RankedValue.HARDCODED:
        self._check_deprecated(dest, kwargs)

        mutex_dest = kwargs.get('mutually_exclusive_group')
        if mutex_dest:
          mutex_map[mutex_dest].append(dest)
          dest = mutex_dest
        else:
          mutex_map[dest].append(dest)

        if len(mutex_map[dest]) > 1:
          raise self.MutuallyExclusiveOptionError(
            "Can only provide one of the mutually exclusive options {}".format(mutex_map[dest]))

      setattr(namespace, dest, val)

    # See if there are any unconsumed flags remaining.
    if flag_value_map:
      raise ParseError('Unrecognized command line flags on {}: {}'.format(
        self._scope_str(), ', '.join(flag_value_map.keys())))

    return namespace
806150
def _add_default_arguments(parser):
    
    parser.add_argument('-c', '--config', action='store', dest='config',
                        help='Path to the configuration file')
    parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',
                        help='Run the application interactively')
345604
def make_argparser():
    
    parser = argparse.ArgumentParser(prog='mypolr',
                                     description="Interacts with the Polr Project's API.\n\n"
                                                 "User Guide and documentation: https://mypolr.readthedocs.io",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     epilog="NOTE: if configurations are saved, they are stored as plain text on disk, "
                                            "and can be read by anyone with access to the file.")
    parser.add_argument("-v", "--version", action="store_true", help="Print version and exit.")

    parser.add_argument("url", nargs='?', default=None, help="The url to process.")

    api_group = parser.add_argument_group('API server arguments',
                                          'Use these for configure the API. Can be stored locally with --save.')

    api_group.add_argument("-s", "--server", default=None, help="Server hosting the API.")
    api_group.add_argument("-k", "--key", default=None, help="API_KEY to authenticate against server.")
    api_group.add_argument("--api-root", default=DEFAULT_API_ROOT,
                           help="API endpoint root.")

    option_group = parser.add_argument_group('Action options',
                                             'Configure the API action to use.')

    option_group.add_argument("-c", "--custom", default=None,
                              help="Custom short url ending.")
    option_group.add_argument("--secret", action="store_true",
                              help="Set option if using secret url.")
    option_group.add_argument("-l", "--lookup", action="store_true",
                              help="Perform lookup action instead of shorten action.")

    manage_group = parser.add_argument_group('Manage credentials',
                                             'Use these to save, delete or update SERVER, KEY and/or '
                                             'API_ROOT locally in ~/.mypolr/config.ini.')

    manage_group.add_argument("--save", action="store_true",
                              help="Save configuration (including credentials) in plaintext(!).")
    manage_group.add_argument("--clear", action="store_true",
                              help="Clear configuration.")
    return parser
395130
def _create_parser() -> ArgumentParser:
    
    parser = ArgumentParser(prog=EXECUTABLE_NAME, description=f"{DESCRIPTION} (v{VERSION})")
    parser.add_argument(
        f"-{VERBOSE_SHORT_PARAMETER}", action="count", default=0,
        help="increase the level of log verbosity (add multiple increase further)")
    subparsers = parser.add_subparsers(dest=ACTION_CLI_PARAMETER_ACCESS, help="action")

    unlock_subparser = subparsers.add_parser(Action.UNLOCK.value, help="release a lock")
    unlock_subparser.add_argument(
        f"-{REGEX_KEY_ENABLED_SHORT_PARAMETER}", action="store_true", default=DEFAULT_REGEX_KEY_ENABLED,
        help="whether the key should be treated as a regular expression and to release all matching locks")

    lock_subparser = subparsers.add_parser(Action.LOCK.value, help="acquire a lock")
    lock_and_execute_subparser = subparsers.add_parser(Action.EXECUTE.value, help="call executable whilst holding lock")

    for subparser in (lock_subparser, lock_and_execute_subparser):
        subparser.add_argument(
            f"--{SESSION_TTL_LONG_PARAMETER}", type=float, default=DEFAULT_SESSION_TTL,
            help=f"time to live (ttl) in seconds of the session that will be created to hold the lock. Must be between "
                 f"{MIN_LOCK_TIMEOUT_IN_SECONDS}s and {MAX_LOCK_TIMEOUT_IN_SECONDS}s (inclusive). If set to "
                 f"{NO_EXPIRY_SESSION_TTL_CLI_PARAMETER_VALUE}, the session will not expire")
        subparser.add_argument(
            f"--{NON_BLOCKING_LONG_PARAMETER}", action="store_true",
            default=DEFAULT_NON_BLOCKING, help="do not block if cannot lock straight away")
        subparser.add_argument(
            f"--{TIMEOUT_LONG_PARAMETER}", default=DEFAULT_TIMEOUT, type=float,
            help="give up trying to acquire the key after this many seconds (where 0 is never)")
        subparser.add_argument(
            f"--{METADATA_LONG_PARAMETER}", default=DEFAULT_METADATA, type=str, action=_ParseJsonAction,
            help="additional metadata to add to the lock information (will be converted to JSON)")
        subparser.add_argument(
            f"--{ON_BEFORE_LOCK_LONG_PARAMETER}", default=[], type=str, nargs="+", action="append",
            help="path to executable that is to be called before an attempt is made to acquire a lock, where the lock "
                 "key is passed as the first argument. Any failures of this executable are ignored")
        subparser.add_argument(
            f"--{ON_LOCK_ALREADY_LOCKED_LONG_PARAMETER}", default=[], type=str, nargs="+", action="append",
            help="path to executable that is to be called after an attempt has been made to acquire a lock but failed "
                 "due to the lock already been taken, where the lock key is passed as the first argument. Any failures "
                 "of this executable are ignored")
        subparser.add_argument(
            f"-{LOCK_POLL_INTERVAL_SHORT_PARAMETER}", default=DEFAULT_LOCK_POLL_INTERVAL_GENERATOR(1), type=float,
            help="number of seconds between polls to acquire a locked lock")

    # XXX: probably a better way of iterating subparsers on `subparsers`
    for subparser in [unlock_subparser, lock_subparser, lock_and_execute_subparser]:
        subparser.add_argument(
            KEY_PARAMETER, type=str, help="the lock identifier")

    lock_and_execute_subparser.add_argument(
        EXECUTABLE_PARAMETER, type=str, help="to execute in shell")

    return parser
1138703
def add_command_line_options_optparse(cls, optparser):
        """"""

        def set_parameter(option, opt, value, parser):
            """callback function for OptionParser"""
            cls.config[opt] = value
            if opt == "--stomp-conf":
                cls.load_configuration_file(value)

        optparser.add_option(
            "--stomp-host",
            metavar="HOST",
            default=cls.defaults.get("--stomp-host"),
            help="Stomp broker address, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-port",
            metavar="PORT",
            default=cls.defaults.get("--stomp-port"),
            help="Stomp broker port, default '%default'",
            type="int",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-user",
            metavar="USER",
            default=cls.defaults.get("--stomp-user"),
            help="Stomp user, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-pass",
            metavar="PASS",
            default=cls.defaults.get("--stomp-pass"),
            help="Stomp password",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-prfx",
            metavar="PRE",
            default=cls.defaults.get("--stomp-prfx"),
            help="Stomp namespace prefix, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-conf",
            metavar="CNF",
            default=cls.defaults.get("--stomp-conf"),
            help="Stomp configuration file containing connection information, disables default values",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
4676
def main(args=None):
    
    parser = ArgumentParser(usage=__usage__)
    parser.add_argument("--no-skip-hidden", action="store_false",
                        dest="skip_hidden",
                        help="Do not skip hidden files. "
                        "Use this if you know what you are doing...")
    parser.add_argument("--include", dest="includes", action="append",
                        help="Only replace in files matching theses patterns")
    parser.add_argument("--exclude", dest="excludes", action="append",
                        help="Ignore files matching theses patterns")
    parser.add_argument("--backup",
                        action="store_true", dest="backup",
                        help="Create a backup for each file. "
                             "By default, files are modified in place")
    parser.add_argument("--go",
                        action="store_true", dest="go",
                        help="Perform changes rather than just printing then")
    parser.add_argument("--dry-run", "-n",
                        action="store_false", dest="go",
                        help="Do not change anything. This is the default")
    parser.add_argument("--color", choices=["always", "never", "auto"],
                        help="When to colorize the output. "
                             "Default: when output is a tty")
    parser.add_argument("--no-color", action="store_false", dest="color",
                        help="Do not colorize output")
    parser.add_argument("--quiet", "-q", action="store_true", dest="quiet",
                        help="Do not produce any output")
    parser.add_argument("pattern")
    parser.add_argument("replacement")
    parser.add_argument("paths", nargs="*")

    parser.set_defaults(
        includes=list(),
        excludes=list(),
        skip_hidden=True,
        backup=False,
        go=False,
        color="auto",
        quiet=False,
        )

    args = parser.parse_args(args=args)
    setup_colors(args)
    repl_main(args)
649857
def make_argparser():
    """"""

    if PY2:
        def unicode_arg(val):
            return val.decode(sys.getfilesystemencoding() or 'utf8')
    else:
        unicode_arg = str

    # Generic options
    p_main = ArgumentParser()
    generic = p_main.add_argument_group("generic arguments")
    generic.add_argument("-q", "--quiet",
                         action='store_true', dest='quiet', default=False,
                         help="silence information messages")
    generic.add_argument("-f", "--force",
                         action='store_true', dest='force', default=False,
                         help="Kill connections automatically if they prevent a command from executing. "
                              "Rename existing databases that are in the way.")
    generic.add_argument("--traceback", action='store_true', default=False,
                         help="print traceback when an error occurs")
    generic.add_argument("--host", metavar="HOST",
                         help="hostname of database server")
    generic.add_argument("-p", "--port", metavar="PORT", type=int,
                         help="port number of database server")

    sub = p_main.add_subparsers(metavar="COMMAND", dest='cmd')

    p_cp = sub.add_parser('cp', description=cmd_copy.__doc__,
                          help="Create a copy of a database within a server")
    p_mv = sub.add_parser('mv', description=cmd_move.__doc__,
                          help="Rename a database within a server")

    for p_cmd in (p_cp, p_mv):
        p_cmd.add_argument('src', metavar="SOURCE", type=unicode_arg,
                           help="source database name")
        p_cmd.add_argument('dest', metavar="DEST", type=unicode_arg,
                           help="destination database name")
        p_cmd.add_argument("--no-backup",
                           action='store_true', dest='no_backup', default=False,
                           help="drop existing DEST database if it exists")

    p_kill = sub.add_parser('kill', description=cmd_kill.__doc__,
                            help="Terminate active connections to a database")
    p_kill.add_argument('databases', metavar="DBNAME", type=unicode_arg, nargs='+',
                        help="kill connections on this database")

    p_reindex = sub.add_parser('reindex', description=cmd_reindex.__doc__,
                               help="Gracefully recreate an index")
    p_reindex.add_argument('-d', '--database', metavar="DB", type=unicode_arg,
                           help="apply reindex in this database")
    p_reindex.add_argument('indexes', metavar="IDXNAME", type=unicode_arg, nargs='+',
                           help="reindex these indexes")

    return p_main
963030
def _default_parser(self):
        
        parser = ArgumentParser(prog='enaml-native')

        #: Build commands by name
        cmds = {c.title: c for c in self.commands}

        #: Build parser, prepare commands
        subparsers = parser.add_subparsers()
        for c in self.commands:
            p = subparsers.add_parser(c.title, help=c.help)
            c.parser = p
            for (flags, kwargs) in c.args:
                p.add_argument(*flags.split(), **kwargs)
            p.set_defaults(cmd=c)
            c.ctx = self.ctx
            c.cmds = cmds
            c.cli = self

        return parser
545925
def create_argument_parser():
    
    parser = argparse.ArgumentParser(prog='lograptor', description=__description__, add_help=False)
    parser.usage = """%(prog)s [options] PATTERN [FILE ...]
    %(prog)s [options] [-e PATTERN | -f FILE] [FILE ...]
    Try '%(prog)s --help' for more information."""

    group = parser.add_argument_group("General Options")
    group.add_argument(
        "--conf", dest="cfgfiles", action='append', default=None, metavar="FILE",
        help="use a specific configuration file"
    )
    group.add_argument(
        "-d", dest="loglevel", default=2, type=int, metavar="[0-4]", choices=range(5),
        help="Logging level (default is 2, use 4 for debug). A level of 0 suppress also "
             "error messages about nonexistent or unreadable files."
    )
    group.add_argument('-V', '--version', action='version', version=__version__)
    group.add_argument('--help', action='help', help="show this help message and exit")

    group = parser.add_argument_group("Scope Selection")
    group.add_argument(
        "-a", "--apps", metavar='APP[,APP...]', type=comma_separated_string,
        default=[], help="process the log lines related to a list of applications"
    )
    group.add_argument(
        "--hosts", metavar="HOSTNAME/IP[,HOSTNAME/IP...]", type=comma_separated_string,
        default=[], help="process the log lines related to an hostname/IP"
    )
    group.add_argument(
        "-F", "--filter", metavar="FIELD=PATTERN[,FIELD=PATTERN...]",
        action="append", dest="filters", type=filter_spec, default=[],
        help="process the log lines that match all the conditions for rule's field values"
    )
    group.add_argument(
        "--time", metavar="HH:MM,HH:MM", type=TimeRange, action="store", dest="time_range",
        help="process the log lines related to a time range"
    )
    group.add_argument(
        "--date", metavar="[YYYY]MMDD[,[YYYY]MMDD]", action="store", dest="time_period",
        type=date_interval_spec, help="restrict the search scope to a date or a date interval"
    )
    group.add_argument(
        "--last", action="store", dest="time_period", type=last_period_spec,
        metavar="[hour|day|week|month|Nh|Nd|Nw|Nm]",
        help="restrict the search scope to a previous time period"
    )

    group = parser.add_argument_group("Matcher Selection")
    group.add_argument(
        "-G", "--ruled", dest='matcher', action=StoreOptionAction,
        help="use patterns and application rules (default)"
    )
    group.add_argument(
        "-X", "--unruled", dest='matcher', action=StoreOptionAction,
        help="use patterns only, skip application rules"
    )
    group.add_argument(
        "-U", "--unparsed", dest='matcher', action=StoreOptionAction,
        help="match the patterns, don't match any application rule"
    )

    group = parser.add_argument_group("Matching Control")
    group.add_argument(
        "-e", "--regexp", metavar="PATTERN", dest="patterns", default=[],
        action="append", help="use PATTERN for matching"
    )
    group.add_argument(
        "-f", "--file", metavar="FILE", dest="pattern_files", default=[],
        action="append", help="obtain patterns from FILE"
    )
    group.add_argument(
        "-i", "--ignore-case", action="store_true", dest="case", default=False,
        help="ignore case distinctions"
    )
    group.add_argument(
        "-v", "--invert-match", action="store_true", dest="invert", default=False,
        help="invert the sense of patterns regexp matching"
    )
    group.add_argument(
        "-w", "--word-regexp", action="store_true", dest="word", default=False,
        help="force PATTERN to match only whole words"
    )

    group = parser.add_argument_group("General Output Control")
    group.add_argument(
        "--output", default=['stdout'], metavar='CHANNEL[,CHANNEL...]', dest='channels',
        type=comma_separated_string, help="send output to channels (default: ['stdout'])"
    )
    group.add_argument(
        "-c", "--count", action="store_true", default=False,
        help="print only a count of matching lines per FILE"
    )
    group.add_argument(
        "--color", default='auto', nargs='?', choices=['auto', 'always', 'never'],
        help="use markers to highlight the matching strings"
    )
    group.add_argument(
        "-L", "--files-without-match", action="store_false", dest="files_with_match", default=None,
        help="print only names of FILEs containing no match"
    )
    group.add_argument(
        "-l", "--files-with-match", action="store_true", dest="files_with_match",
        help="print only names of FILEs containing matches"
    )
    group.add_argument(
        "-m", "--max-count", metavar='NUM', action="store", type=positive_integer, default=0,
        help="stop after NUM matches"
    )
    group.add_argument(
        "-o", "--only-matching", action="store_true", default=False,
        help="show only the part of a line matching PATTERN"
    )
    group.add_argument(
        "-q", "--quiet", action="store_true", default=False, help="suppress all normal output"
    )
    group.add_argument(
        "-s", "--no-messages", action="store_const", const=0, dest='loglevel',
        help="suppress error messages (equivalent to -d 0)"
    )

    group = parser.add_argument_group("Output Data Control")
    group.add_argument(
        "--report", metavar='NAME', nargs='?', default=False,
        help="produce a report at the end of processing"
    )
    group.add_argument(
        "--ip-lookup", action="store_true", default=False,
        help="translate IP addresses to DNS names"
    )
    group.add_argument(
        "--uid-lookup", action="store_true", default=False,
        help="translate UIDs to usernames"
    )
    group.add_argument(
        "--anonymize", action="store_true", default=False,
        help="anonymize defined rule's fields value"
    )

    group = parser.add_argument_group("Output Line Prefix Control")
    group.add_argument(
        "-n", "--line-number", action="store_true", default=False,
        help="print line number with output lines"
    )
    group.add_argument(
        "-H", "--with-filename", action="store_true", dest="with_filename", default=None,
        help="print the file name for each match"
    )
    group.add_argument(
        "-h", "--no-filename", action="store_false", dest="with_filename", default=None,
        help="suppress the file name prefix on output"
    )

    group = parser.add_argument_group("Context Line Control")
    group.add_argument(
        "-T", "--thread", action="store_true", default=False,
        help="the context is the log thread of the application"
    )
    group.add_argument(
        "-B", "--before-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of leading context"
    )
    group.add_argument(
        "-A", "--after-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of trailing context"
    )
    group.add_argument(
        "-C", "--context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of output context"
    )
    group.add_argument(
        "--group-separator", metavar='SEP', default='--',
        help="use SEP as a group separator. By default SEP is double hyphen (--)."
    )
    group.add_argument(
        "--no-group-separator", dest="group_separator", action="store_const", const='',
        help="use empty string as a group separator"
    )

    group = parser.add_argument_group("File and Directory Selection")
    group.add_argument(
        "-r", "--recursive", action="store_true", default=False,
        help="read all files under each directory, recursively"
    )
    group.add_argument(
        "-R", "--dereference-recursive", action="store_true", default=False,
        help="likewise, but follow all symlinks"
    )
    group.add_argument(
        "--include", metavar='GLOB', default=[], action="append",
        help="search only files that match GLOB"
    )
    group.add_argument(
        "--exclude", metavar='GLOB', default=[], action="append",
        help="skip files and directories matching GLOB"
    )
    group.add_argument(
        "--exclude-from", metavar='FILE', default=[], action="append",
        help="skip files matching any file pattern from FILE"
    )
    group.add_argument(
        "--exclude-dir", metavar='DIR', default=[], action="append",
        help="exclude directories matching the pattern DIR"
    )

    parser.add_argument(
        'files', metavar='[FILE ...]', nargs='*',
        help='Input files. Each argument can be a file path or a glob pathname. '
             'A "-" stands for standard input. If no arguments are given then processes '
             'all the files included within the scope of the selected applications.'
    )
    return parser
1253529
def parse_args_and_run():
    
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='Docker-tag-naming sub-commands',
                                       dest='subparser_name')

    #
    #   Forge
    #
    parser_forge = subparsers.add_parser('forge',
                                         help='Create a new version tag')
    parser_forge.add_argument('--version', type=int, default=1,
                              help='Version number')
    parser_forge.add_argument('--commit-id', required=True,
                              help='Git commit id')
    parser_forge.add_argument('--branch', required=True,
                              help='The branch name (ie. master)')

    #
    #   Latest
    #
    parser_latest = subparsers.add_parser('latest',
                                          help='Query the latest tag in the'
                                               ' registry')
    parser_latest.add_argument('image',
                               help='The image to query (ie. username/image)')
    parser_latest.add_argument('branch',
                               help='The branch name (ie. master)')

    #
    #   Bump
    #
    parser_bump = subparsers.add_parser('bump',
                                        help='Query the latest tag in the'
                                             ' registry and return a +1')
    parser_bump.add_argument('image',
                             help='The image to bump (ie. username/image)')
    parser_bump.add_argument('branch',
                             help='The branch name (ie. master)')
    parser_bump.add_argument('--commit-id', required=True,
                             help='Git commit id for the newly created tag')

    #
    #   Refresh
    #
    parser_latest = subparsers.add_parser('refresh',
                                          help='Loop until the latest tag in'
                                               ' the registry changes')
    parser_latest.add_argument('image',
                               help='The image to query (ie. username/image)')
    parser_latest.add_argument('branch',
                               help='The branch name (ie. master)')

    args = parser.parse_args()

    {'bump': run_bump,
     'latest': run_latest,
     'forge': run_forge,
     'refresh': run_refresh}.get(args.subparser_name)(args)
830393
def parse_command_line_arguments(argparse_parser, init_indent=5, subs_indent=5,
                                 line_width=76):
    """"""
    # Redirect stdout and stderr to prettify help or usage output from argparse.
    old_stdout = sys.stdout # save stdout
    old_stderr = sys.stderr # save stderr
    sys.stdout = RedirectHelp(sys.stdout, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stdout to add postprocessor
    sys.stderr = RedirectHelp(sys.stderr, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stderr to add postprocessor

    # Run the actual argument-parsing operation via argparse.
    args = argparse_parser.parse_args()

    # The argparse class has finished its argument-processing, so now no more
    # usage or help messages will be printed.  So restore stdout and stderr
    # to their usual settings, except with self-flushing added.
    sys.stdout = SelfFlushingOutstream(old_stdout)
    sys.stderr = SelfFlushingOutstream(old_stderr)

    return args
1210595
def init_parser():
    """"""

    usage = "Usage: %(prog)s <option(s)> <file(s)>"
    description = " Display information from object <file(s)>.\n"
    description += " At least one of the following switches must be given:"

    #
    # Create an argument parser and an exclusive group.
    #
    parser = ArgumentParser(
        usage=usage, description=description, add_help=False)

    group = parser.add_mutually_exclusive_group()

    #
    # Add objdump parameters.
    #
    group.add_argument("-a", "--archive-headers",
        action=DumpArchieveHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display archive header information")

    group.add_argument("-f", "--file-headers",
        action=DumpFileHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display the contents of the overall file header")

    #group.add_argument("-p", "--private-headers",    action="store", type=FileType("r"), nargs="+", help="Display object format specific file header contents")
    #group.add_argument("-P", "--private=OPT,OPT...", action="store", type=FileType("r"), nargs="+", help="Display object format specific contents")

    group.add_argument("-h", "--section-headers",
        action=DumpSectionHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display the contents of the section headers")

    #group.add_argument("-x", "--all-headers",        action="store", type=FileType("r"), nargs="+", help="Display the contents of all headers")

    group.add_argument("-d", "--disassemble",
        action=DisassembleSectionAction,
        type=FileType("r"), nargs="+",
        help="Display assembler contents of executable sections")


    group.add_argument("-D", "--disassemble-all",
        action=DisassembleSectionsAction,
        type=FileType("r"), nargs="+",
        help="Display assembler contents of executable sections")

    #group.add_argument("-S", "--source",             action="store", type=FileType("r"), nargs="+", help="Intermix source code with disassembly")

    group.add_argument("-s", "--full-contents",
        action=DumpSectionContentAction,
        type=FileType("r"), nargs="+",
        help="Display the full contents of all sections requested")

    #group.add_argument("-g", "--debugging",          action="store", type=FileType("r"), nargs="+", help="Display debug information in object file")
    #group.add_argument("-e", "--debugging-tags",     action="store", type=FileType("r"), nargs="+", help="Display debug information using ctags style")
    #group.add_argument("-G", "--stabs",              action="store", type=FileType("r"), nargs="+", help="Display (in raw form) any STABS info in the file")

    #-W[lLiaprmfFsoRt] or")
    #--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,")
    #      =frames-interp,=str,=loc,=Ranges,=pubtypes,")
    #      =gdb_index,=trace_info,=trace_abbrev,=trace_aranges]")
    #                       Display DWARF info in the file")

    group.add_argument("-t", "--syms",
        action=DumpFileSymbols,
        type=FileType("r"), nargs="+",
        help="Display the contents of the symbol table(s)")

    #-T, --dynamic-syms       Display the contents of the dynamic symbol table")
    #-r, --reloc              Display the relocation entries in the file")
    #-R, --dynamic-reloc      Display the dynamic relocation entries in the file")

    group.add_argument("-v", "--version", action="version",
        version="%%(prog)s %s (%s)" % (__version__, __description__),
        help="Display this program's version number")

    group.add_argument("-i", "--info",
        action=ListFormatAndArchitecturesInformationAction,
        nargs=REMAINDER,
        help="List object formats and architectures supported")

    group.add_argument("-H", "--help", action="store_true", default=False,
        help="Display this information")

    return parser
18997
def arg_default(*args, **kwargs):
    
    parser = argparse.ArgumentParser()
    parser.add_argument(*args, **kwargs)
    args = vars(parser.parse_args([]))
    _, default = args.popitem()
    return default
291936
def create_parser():
    """"""
    from argparse import ArgumentParser, FileType

    description = ("PEP8 clean only the parts of the files which you have "
                   "touched since the last commit, a previous commit or "
                   "(the merge-base of) a branch.")
    epilog = ("Run before you commit, against a previous commit or "
              "branch before merging.")
    parser = ArgumentParser(description=description,
                            epilog=epilog,
                            prog='pep8radius')

    parser.add_argument('rev',
                        help='commit or name of branch to compare against',
                        nargs='?')

    parser.add_argument('--version',
                        help='print version number and exit',
                        action='store_true')

    parser.add_argument('-d', '--diff', action='store_true', dest='diff',
                        help='print the diff of fixed source vs original')
    parser.add_argument('--error-status', action='store_true',
                        dest='error_status',
                        help="return a shell status code of 1 if there are"
                             " any fixes")
    parser.add_argument('-i', '--in-place', action='store_true',
                        help="make the fixes in place; modify the files")
    parser.add_argument('--no-color', action='store_true',
                        help='do not print diffs in color '
                             '(default is to use color)')
    parser.add_argument('-v', '--verbose', action='count', dest='verbose',
                        default=0,
                        help='print verbose messages; '
                        'multiple -v result in more verbose messages '
                        '(one less -v is passed to autopep8)')
    parser.add_argument('--from-diff', type=FileType('r'), metavar='DIFF',
                        help="Experimental: rather than calling out to version"
                             " control, just pass in a diff; "
                             "the modified lines will be fixed")

    ap = parser.add_argument_group('pep8', 'Pep8 options to pass to autopep8.')
    ap.add_argument('-p', '--pep8-passes', metavar='n',
                    default=-1, type=int,
                    help='maximum number of additional pep8 passes '
                    '(default: infinite)')
    ap.add_argument('-a', '--aggressive', action='count', default=0,
                    help='enable non-whitespace changes; '
                    'multiple -a result in more aggressive changes')
    ap.add_argument('--experimental', action='store_true',
                    help='enable experimental fixes')
    ap.add_argument('--exclude', metavar='globs',
                    help='exclude file/directory names that match these '
                    'comma-separated globs')
    ap.add_argument('--list-fixes', action='store_true',
                    help='list codes for fixes and exit; '
                    'used by --ignore and --select')
    ap.add_argument('--ignore', metavar='errors', default='',
                    help='do not fix these errors/warnings '
                    '(default: {0})'.format(DEFAULT_IGNORE))
    ap.add_argument('--select', metavar='errors', default='',
                    help='fix only these errors/warnings (e.g. E4,W)')
    ap.add_argument('--max-line-length', metavar='n', default=79, type=int,
                    help='set maximum allowed line length '
                    '(default: %(default)s)')
    ap.add_argument('--indent-size', default=DEFAULT_INDENT_SIZE,
                    type=int, metavar='n',
                    help='number of spaces per indent level '
                    '(default %(default)s)')

    df = parser.add_argument_group('docformatter',
                                   'Fix docstrings for PEP257.')
    df.add_argument('-f', '--docformatter', action='store_true',
                    help='Use docformatter')
    df.add_argument('--no-blank', dest='post_description_blank',
                    action='store_false',
                    help='Do not add blank line after description')
    df.add_argument('--pre-summary-newline',
                    action='store_true',
                    help='add a newline before the summary of a '
                    'multi-line docstring')
    df.add_argument('--force-wrap', action='store_true',
                    help='force descriptions to be wrapped even if it may '
                    'result in a mess')

    cg = parser.add_argument_group('config',
                                   'Change default options based on global '
                                   'or local (project) config files.')
    cg.add_argument('--global-config',
                    default=DEFAULT_CONFIG,
                    metavar='filename',
                    help='path to global pep8 config file; ' +
                    " if this file does not exist then this is ignored" +
                    '(default: %s)' % DEFAULT_CONFIG)
    cg.add_argument('--ignore-local-config', action='store_true',
                    help="don't look for and apply local config files; "
                    'if not passed, defaults are updated with any '
                    "config files in the project's root directory")

    yp = parser.add_argument_group('yapf',
                                   'Options for yapf, alternative to autopep8. '
                                   'Currently any other options are ignored.')
    yp.add_argument('-y', '--yapf', action='store_true',
                    help='Use yapf rather than autopep8. '
                    'This ignores other arguments outside of this group.')
    yp.add_argument('--style', metavar='', default='pep8',
                    help='style either pep8, google, name of file with style'
                    'settings, or a dict')

    return parser
599093
def add_parser_arguments():
    """"""
    argparser = parser.get()
    argparser.add_argument('-P', '--profile',
                           action='store',
                           default=None,
                           dest='profile',
                           help='Profile the consumer modules, specifying '
                           'the output directory.')
    argparser.add_argument('-o', '--only',
                           action='store',
                           default=None,
                           dest='consumer',
                           help='Only run the consumer specified')
    argparser.add_argument('-p', '--prepend-path',
                           action='store',
                           default=None,
                           dest='prepend_path',
                           help='Prepend the python path with the value.')
    argparser.add_argument('-q', '--qty',
                           action='store',
                           type=int,
                           default=None,
                           dest='quantity',
                           help='Run the specified quantity of consumer '
                           'processes when used in conjunction with -o')
    argparser.add_argument('--version', action='version',
                           version='%(prog)s {}'.format(__version__))