Add the cookbook management command and arguments.

    :rtype: argparse.ArgumentParser
332688
def add_cookbook_mgmt_options(parser):
    
    cookbook = parser.add_parser('cookbook', help='Invoke in a Jenkins job to '
                                                  'update a cookbook in '
                                                  'chef-repo')
    cookbook.add_argument('repo', action='store',
                          help='Git URL for chef-repo')
    cookbook.set_defaults(func='process_cookbook')
87117
def add_arguments(parser, default_level=logging.INFO):
	
	adder = (
		getattr(parser, 'add_argument', None)
		or getattr(parser, 'add_option')
	)
	adder(
		'-l', '--log-level', default=default_level, type=log_level,
		help="Set log level (DEBUG, INFO, WARNING, ERROR)")
822695
def add_argument(self, parser, set_default=False):
        
        default = self.default if set_default else None
        kwargs = dict(
            nargs=self.nargs,
            default=default,
            help="%s [%s]" % (self.short, default)
        )
        kwargs.update(self.extra)
        if self.flags:
            args = tuple(self.flags)
            kwargs.update({'dest': self.name,
                           'action': self.action or "store"})
            if kwargs["action"] != "store":
                kwargs.pop("type", None)
                kwargs.pop("nargs", None)
        elif self.nargs and self.name:
            args = (self.name,)
            kwargs.update({'metavar': self.meta or None})
        else:
            # Not added to argparser
            return
        if self.meta:
            kwargs['metavar'] = self.meta
        parser.add_argument(*args, **kwargs)
1154976
def add_arguments(self, parser):
        """"""
        parser.add_argument('app_label', nargs='*')
        for argument in self.arguments:
            parser.add_argument(*argument.split(' '), **self.arguments[argument])
775330
def command_parser():
    

    class Parser(argparse.ArgumentParser):
        # print usages and exit on errors
        def error(self, message):
            print("\x1b[1;31merror: \x1b[0m{}".format(message))
            self.print_help()
            self.exit(1)

        # hide choices on errors
        def _check_value(self, action, value):
            if action.choices is not None and value not in action.choices:
                raise argparse.ArgumentError(
                    action, "invalid choice: '{}'".format(value)
                )

    # make parser
    parser = Parser(formatter_class=argparse.RawTextHelpFormatter)

    # parser: add verbose, version
    for short, name, msg in INFORMATION:
        short = "-%s" % short
        arg = "--%s" % name
        parser.add_argument(short, arg, action="store_true", help=msg)

    # make subparsers // ALIAS_DEPRECATION: remove metavar later
    metavar = "{click,list,refresh}"
    subparsers = parser.add_subparsers(dest="command", metavar=metavar)
    sps = {}

    # subparsers: add click, list, refresh... hide docstring
    data = {"formatter_class": argparse.RawTextHelpFormatter}
    for name, msg, nargs in SUBPARSERS:
        data.update({"epilog": EPILOGS[name], "help": msg})
        # don't show docstring in py3-cmd --help
        if name in ["docstring"]:
            del data["help"]
        sps[name] = subparsers.add_parser(name, **data)
        sps[name].add_argument(nargs=nargs, dest="module", help="module name")

    # ALIAS_DEPRECATION: subparsers: add click (aliases)
    buttons = {
        "leftclick": 1,
        "middleclick": 2,
        "rightclick": 3,
        "scrollup": 4,
        "scrolldown": 5,
    }
    for name in sorted(buttons):
        sps[name] = subparsers.add_parser(name)
        sps[name].add_argument(nargs="+", dest="module", help="module name")

    # click subparser: add button, index, width, height, relative_{x,y}, x, y
    sp = sps["click"]
    for name, msg in CLICK_OPTIONS:
        arg = "--{}".format(name)
        if name == "button":
            sp.add_argument(arg, metavar="INT", type=int, help=msg, default=1)
        elif name == "index":
            sp.add_argument(arg, metavar="INDEX", help=msg)
        elif name == "modifiers":
            sp.add_argument(arg, metavar="KEY", help=msg)
        else:
            sp.add_argument(arg, metavar="INT", type=int, help=msg)

    # docstring subparser: add check, diff, update
    sp = sps["docstring"]
    for name, msg in DOCSTRING_OPTIONS:
        arg = "--{}".format(name)
        sp.add_argument(arg, action="store_true", help=msg)

    # refresh subparser: add all
    sp = sps["refresh"]
    for name, msg in REFRESH_OPTIONS:
        arg = "--{}".format(name)
        sp.add_argument(arg, action="store_true", help=msg)

    # list subparser: add all, core, user, full
    sp = sps["list"]
    for short, name, msg in LIST_OPTIONS:
        name = "--{}".format(name)
        if short:
            short = "-{}".format(short)
            sp.add_argument(short, name, action="store_true", help=msg)
        else:
            sp.add_argument(name, action="store_true", help=msg)

    # parse args, post-processing
    options = parser.parse_args()

    if options.command == "click":
        # cast string index to int
        if options.index:
            try:
                options.index = int(options.index)
            except ValueError:
                pass
        # specify modifiers, optionally joined by plus signs
        if options.modifiers:
            options.modifiers = options.modifiers.split("+")
        else:
            options.modifiers = []
    elif options.command == "refresh":
        # refresh all
        # ALL_DEPRECATION
        if options.module is None:
            options.module = []
        # end
        valid = False
        if options.all:  # keep this
            options.command = "refresh_all"
            options.module = []
            valid = True
        if "all" in options.module:  # remove this later
            options.command = "refresh_all"
            options.module = []
            valid = True
        if not options.module and not valid:
            sps["refresh"].error("missing positional or optional arguments")
    elif options.command in ["list", "docstring"]:
        parse_list_or_docstring(options, sps)
        parser.exit()
    elif options.version:
        # print version
        from platform import python_version
        from py3status.version import version

        print("py3status {} (python {})".format(version, python_version()))
        parser.exit()
    elif not options.command:
        parser.error("too few arguments")

    # ALIAS_DEPRECATION
    alias = options.command in buttons

    # py3-cmd click 3 dpms ==> py3-cmd click --button 3 dpms
    new_modules = []
    for index, name in enumerate(options.module):
        if name.isdigit():
            if alias:
                continue
            if not index:  # zero index
                options.button = int(name)
        else:
            new_modules.append(name)

    # ALIAS_DEPRECATION: Convert (click) aliases to buttons
    if alias:
        options.button = buttons[options.command]
        options.command = "click"

    if options.command == "click" and not new_modules:
        sps[options.command].error("too few arguments")
    options.module = new_modules

    return options
703289
def command_line():
    '''
    
    '''
    description = 'Kan helps you find the book'
    version     = ' '.join([__version__, __release__])
    parser      = ArgumentParser(prog='kan', description=description)

    subparser   = parser.add_subparsers(help='Search by')

    by_title    = subparser.add_parser('title', help='Book title',)
    by_title.add_argument('title', help='Book name')

    by_isbn     = subparser.add_parser('isbn', help='ISBN code')
    by_isbn.add_argument('code', help='Valid ISBN code')

    by_author   = subparser.add_parser('author', help='Book author')
    by_author.add_argument('author', help='Authors name')
    by_author.add_argument('--recent', help='Search by most recent', action='store_true')
    by_author.add_argument('--top', help='Search by best selling', action='store_true')

    # Main Parser
    parser.add_argument(
        '-v', '--version', action='version',
        version="%s v%s" % ('kan', version),
    )
    parser.add_argument(
        '--title',
        help='Title of the book',
        metavar='name',
    )
    parser.add_argument(
        '--author',
        default=None,
        metavar='name',
        help='Name of the author',
    )
    parser.add_argument(
        '--subject',
        type=str,
        help='Specify subject matter by category',
        metavar='topic',
    )
    parser.add_argument(
        '--max',
        type=int,
        metavar='n',
        default=3,
        choices=range(41),
        help='Maximum results to get per query: default=3, max=40',
    )
    parser.add_argument(
        '--language',
        type=str,
        metavar='code',
        default='',
        help='Restrict the search results to those with a certain language code',
    )
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='Print out debug information',
    )

    return parser.parse_args()
267018
def add_argument_to(self, parser):
        
        from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory
        if isinstance(self.kwargs.get('action', ''), list):
            # see documentation of DefaultIffUsedActionFactory to see why this is necessary
            if self.kwargs['action'][0] == 'default_iff_used':
                self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action(
                    self.kwargs['action'][1])
        # In cli 'preserved' is not supported.
        # It needs to be removed because it is unknown for argparse.
        self.kwargs.pop('preserved', None)
        try:
            parser.add_argument(*self.flags, **self.kwargs)
        except Exception as ex:
            problem = "Error while adding argument '{name}': {error}".\
                format(name=self.name, error=repr(ex))
            raise exceptions.ExecutionException(problem)
1176268
def add_commands(self):
        
        self.parser.add_argument(
            '-d',
            action="count",
            **self.config.default.debug.get_arg_parse_arguments())
991647
def ParseArguments(self):
    
    loggers.ConfigureLogging()

    argument_parser = argparse.ArgumentParser(
        description=self.DESCRIPTION, add_help=False,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    self.AddBasicOptions(argument_parser)

    argument_helper_names = ['storage_file']
    if self._CanEnforceProcessMemoryLimit():
      argument_helper_names.append('process_resources')
    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
        argument_parser, names=argument_helper_names)

    argument_parser.add_argument(
        '--compare', dest='compare_storage_file', type=str,
        action='store', default='', metavar='STORAGE_FILE', help=(
            'The path of the storage file to compare against.'))

    argument_parser.add_argument(
        '--output_format', '--output-format', dest='output_format', type=str,
        choices=['text', 'json'], action='store', default='text',
        metavar='FORMAT', help=(
            'Format of the output, the default is: text. Supported options: '
            'json, text.'))

    argument_parser.add_argument(
        '-v', '--verbose', dest='verbose', action='store_true',
        default=False, help='Print verbose output.')

    argument_parser.add_argument(
        '-w', '--write', metavar='OUTPUTFILE', dest='write',
        help='Output filename.')

    try:
      options = argument_parser.parse_args()
    except UnicodeEncodeError:
      # If we get here we are attempting to print help in a non-Unicode
      # terminal.
      self._output_writer.Write('\n')
      self._output_writer.Write(argument_parser.format_help())
      return False

    try:
      self.ParseOptions(options)
    except errors.BadConfigOption as exception:
      self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
      self._output_writer.Write('\n')
      self._output_writer.Write(argument_parser.format_usage())
      return False

    loggers.ConfigureLogging(
        debug_output=self._debug_mode, filename=self._log_file,
        quiet_mode=self._quiet_mode)

    return True
392212
def add_arguments(self, parser):
        
        parser.add_argument('name', nargs=1, choices=['kinetis'],
                            help='name of MCU to unlock')
        return self.add_common_arguments(parser, True)
770804
def simple_cmd():
    
    parser = argparse.ArgumentParser(
        prog="Simple command-line function toolkit.",
        description="""Input function name and args and kwargs.
        python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""",
    )
    parser.add_argument("-f", "--func_name", default="main")
    parser.add_argument("-a", "--args", dest="args", nargs="*")
    parser.add_argument("-k", "--kwargs", dest="kwargs")
    parser.add_argument(
        "-i",
        "-s",
        "--info",
        "--show",
        "--status",
        dest="show",
        action="store_true",
        help="show the args, kwargs and function's source code.",
    )
    params = parser.parse_args()
    func_name = params.func_name
    func = globals().get(func_name)
    if not (callable(func)):
        Config.utils_logger.warning("invalid func_name: %s" % func_name)
        return
    args = params.args or []
    kwargs = params.kwargs or {}
    if kwargs:
        items = [re.split("[:=]", i) for i in re.split("[,;]+", kwargs)]
        kwargs = dict(items)
    if params.show:
        from inspect import getsource

        Config.utils_logger.info("args: %s; kwargs: %s" % (args, kwargs))
        Config.utils_logger.info(getsource(func))
        return
    func(*args, **kwargs)
1015555
def add_argument(self, parser, permissive=False, **override_kwargs):
        
        kwargs = {}
        required = None
        if self.kwargs:
            kwargs = copy.copy(self.kwargs)
            if 'env' in kwargs and 'help' in kwargs:
                kwargs['help'] = "%s (or set %s)" % (kwargs['help'],
                                                     kwargs['env'])
            if permissive:
                required = kwargs.pop('required', None)
            try:
                del kwargs['env']
            except KeyError:
                pass
            try:
                del kwargs['ini_section']
            except KeyError:
                pass

            # allow custom and/or exclusive argument groups
            if kwargs.get('group') or kwargs.get('mutually_exclusive'):
                groupname = kwargs.pop('group', None) or kwargs.get('dest')
                mutually_exclusive = kwargs.pop('mutually_exclusive', None)
                if not groupname:
                    raise NoGroupForOption(
                        "%s requires either 'group' or 'dest'." % self)
                description = kwargs.pop('group_description', None)
                exists = [grp for grp in parser._action_groups
                          if grp.title == groupname]
                if exists:
                    group = exists[0]
                    if description and not group.description:
                        group.description = description
                else:
                    group = parser.add_argument_group(
                        title=groupname, description=description)
                if mutually_exclusive:
                    if not required:
                        required = kwargs.pop('required', None)
                    mutexg_title = '%s mutually-exclusive-group' % groupname
                    exists = [grp for grp in group._mutually_exclusive_groups
                              if grp.title == mutexg_title]
                    if exists:
                        group = exists[0]
                    else:
                        # extend parent group
                        group = group.add_mutually_exclusive_group(
                            required=required)
                        group.title = mutexg_title
                    # if any in the same group are required, then the
                    # mutually exclusive group should be set to required
                    if required and not group.required:
                        group.required = required
                    self._mutexgroup = group
                self._action = group.add_argument(*self.args, **kwargs)
                return

        kwargs.update(override_kwargs)
        self._action = parser.add_argument(*self.args, **kwargs)
67818
def add_arguments(cls, parser, sys_arg_list=None):
        
        parser.add_argument('--icmp_check_interval',
                            dest='icmp_check_interval',
                            required=False, default=2, type=float,
                            help="ICMPecho interval in seconds, default 2 "
                                 "(only for 'icmpecho' health monitor plugin)")
        return ["icmp_check_interval"]
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()
626847
def create_argument_parser():
    
    parser = argparse.ArgumentParser(prog='haas')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(haas.__version__))
    verbosity = parser.add_mutually_exclusive_group()
    verbosity.add_argument('-v', '--verbose', action='store_const', default=1,
                           dest='verbosity', const=2, help='Verbose output')
    verbosity.add_argument('-q', '--quiet', action='store_const', const=0,
                           dest='verbosity', help='Quiet output')
    parser.add_argument('-f', '--failfast', action='store_true', default=False,
                        help='Stop on first fail or error')
    parser.add_argument('-c', '--catch', dest='catch_interrupt',
                        action='store_true', default=False,
                        help=('(Ignored) Catch ctrl-C and display results so '
                              'far'))
    parser.add_argument('-b', '--buffer', action='store_true', default=False,
                        help='Buffer stdout and stderr during tests')
    parser.add_argument(
        'start', nargs='*', default=[os.getcwd()],
        help=('One or more directories or dotted package/module names from '
              'which to start searching for tests'))
    parser.add_argument('-p', '--pattern', default='test*.py',
                        help="Pattern to match tests ('test*.py' default)")
    parser.add_argument('-t', '--top-level-directory', default=None,
                        help=('Top level directory of project (defaults to '
                              'start directory)'))
    _add_log_level_option(parser)
    return parser
1289528
def _cmdline(argv=None):
    
    parser = ArgumentParser()
    parser.add_argument("-c", "--config", action="append",
            help="config file [etc/config.yml]")
    parser.add_argument("-v", "--version", action="version",
            version="pipsort {:s}".format(__version__),
            help="print version and exit")
    parser.add_argument("-w", "--warn", default="WARNING",
            help="logger warning level [WARNING]")
    parser.add_argument("search_term", type=str,
                        help="Search term for PyPI")
    args = parser.parse_args(argv)
    if not args.config:
        args.config = ["etc/config.yml"]
    return args
706189
def get_application_parser(commands):
    

    parser = argparse.ArgumentParser(
        description=configuration.APPLICATION_DESCRIPTION,
        usage =configuration.EXECUTABLE_NAME + ' [sub-command] [options]',
        add_help=False)

    parser.add_argument(
        'sub_command',
        choices=[name for name in commands],
        nargs="?")

    parser.add_argument("-h", "--help", action="store_true")
    return parser