Add generic command-line arguments to a top-level argparse parser.

        After running this, the results from ``argparse.parse_args()``
        can be passed to :meth:`main`.
426918
def add_arguments(self, parser):
        '''

        '''
        commands = set(name[3:] for name in dir(self) if name.startswith('do_'))
        parser.add_argument('action', help='action to run', nargs='?',
                            choices=list(commands))
        parser.add_argument('arguments', help='arguments specific to ACTION',
                            nargs=argparse.REMAINDER)
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)
1080257
public <A extends BaseArgument> ArgumentParser add(A arg) {
        if (arg instanceof BaseOption) {
            return add((BaseOption) arg);
        }

        // No arguments can be added after a sub-command-set.
        if (arguments.size() > 0 && arguments.get(arguments.size() - 1) instanceof SubCommandSet) {
            throw new IllegalArgumentException("No arguments can be added after a sub-command set");
        }

        arguments.add(arg);
        return this;
    }
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)
895576
def add_arguments(self, parser):
        
        parser.usage = "%(prog)s [options] [ [DIR|FILE|FILE:LINE] ]+"
        parser.description = """\
        Run a number of feature tests with behave."""

        add_command_arguments(parser)
        add_behave_arguments(parser)
507159
def get_command_line_arguments():
    

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("-h",
                        "--help",
                        action="help",
                        help="'Displays this help message and exit.'")

    parser.add_argument("-t",
                        "--title",
                        type=unicode,
                        dest="title",
                        help="'Package title.'")

    parser.add_argument("-i",
                        "--input",
                        type=unicode,
                        dest="input",
                        help="'Input file to convert.'")

    parser.add_argument("-o",
                        "--output",
                        type=unicode,
                        dest="output",
                        help="'Output file.'")

    parser.add_argument("-c",
                        "--content_directory",
                        type=unicode,
                        dest="content_directory",
                        help="'Content directory.'")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    return parser.parse_args()
1337937
def load_args(self, args, clargs):
        
        # Parse All Arguments
        args = self.parser.parse_args(args=clargs, namespace=args)

        # Print the help information if no subcommand is given
        # subcommand is required for operation
        if args.subcommand is None:
            self.parser.print_help()
            args = None

        return args
821719
def create_parser(self, prog_name, subcommand):
        
        parser = argparse.ArgumentParser(prog='%s %s' % (prog_name, subcommand), description=self.help)

        parser.add_argument('-v', '--verbosity', action='store', default=1, type=int, choices=range(4),
            help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output'),
        parser.add_argument('--settings',
            help='The Python path to a settings module, e.g. "myproject.settings.main". '
            'If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
        parser.add_argument('--pythonpath',
            help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
        parser.add_argument('--traceback', action='store_true', help='Print traceback on exception'),

        subparsers = parser.add_subparsers(description='JavaScript command to execute')

        for subparser in self.subparsers:
            subparser(self, subparsers)

        return parser
951733
def main(args):
    

    parser = argparse.ArgumentParser(usage="python -m premailer [options]")

    parser.add_argument(
        "-f",
        "--file",
        nargs="?",
        type=argparse.FileType("r"),
        help="Specifies the input file.  The default is stdin.",
        default=sys.stdin,
        dest="infile",
    )

    parser.add_argument(
        "-o",
        "--output",
        nargs="?",
        type=argparse.FileType("w"),
        help="Specifies the output file.  The default is stdout.",
        default=sys.stdout,
        dest="outfile",
    )

    parser.add_argument("--base-url", default=None, type=str, dest="base_url")

    parser.add_argument(
        "--remove-internal-links",
        default=True,
        help="Remove links that start with a '#' like anchors.",
        dest="preserve_internal_links",
    )

    parser.add_argument(
        "--exclude-pseudoclasses",
        default=False,
        help="Pseudo classes like p:last-child', p:first-child, etc",
        action="store_true",
        dest="exclude_pseudoclasses",
    )

    parser.add_argument(
        "--preserve-style-tags",
        default=False,
        help="Do not delete <style></style> tags from the html document.",
        action="store_true",
        dest="keep_style_tags",
    )

    parser.add_argument(
        "--remove-star-selectors",
        default=True,
        help="All wildcard selectors like '* {color: black}' will be removed.",
        action="store_false",
        dest="include_star_selectors",
    )

    parser.add_argument(
        "--remove-classes",
        default=False,
        help="Remove all class attributes from all elements",
        action="store_true",
        dest="remove_classes",
    )

    parser.add_argument(
        "--capitalize-float-margin",
        default=False,
        help="Capitalize float and margin properties for outlook.com compat.",
        action="store_true",
        dest="capitalize_float_margin",
    )

    parser.add_argument(
        "--strip-important",
        default=False,
        help="Remove '!important' for all css declarations.",
        action="store_true",
        dest="strip_important",
    )

    parser.add_argument(
        "--method",
        default="html",
        dest="method",
        help="The type of html to output. 'html' for HTML, 'xml' for XHTML.",
    )

    parser.add_argument(
        "--base-path",
        default=None,
        dest="base_path",
        help="The base path for all external stylsheets.",
    )

    parser.add_argument(
        "--external-style",
        action="append",
        dest="external_styles",
        help="The path to an external stylesheet to be loaded.",
    )

    parser.add_argument(
        "--css-text",
        action="append",
        dest="css_text",
        help="CSS text to be applied to the html.",
    )

    parser.add_argument(
        "--disable-basic-attributes",
        dest="disable_basic_attributes",
        help="Disable provided basic attributes (comma separated)",
        default=[],
    )

    parser.add_argument(
        "--disable-validation",
        default=False,
        action="store_true",
        dest="disable_validation",
        help="Disable CSSParser validation of attributes and values",
    )

    parser.add_argument(
        "--pretty",
        default=False,
        action="store_true",
        help="Pretty-print the outputted HTML.",
    )

    parser.add_argument(
        "--encoding", default="utf-8", help="Output encoding. The default is utf-8"
    )

    options = parser.parse_args(args)

    if options.disable_basic_attributes:
        options.disable_basic_attributes = options.disable_basic_attributes.split()

    html = options.infile.read()
    if hasattr(html, "decode"):  # Forgive me: Python 2 compatability
        html = html.decode("utf-8")

    p = Premailer(
        html=html,
        base_url=options.base_url,
        preserve_internal_links=options.preserve_internal_links,
        exclude_pseudoclasses=options.exclude_pseudoclasses,
        keep_style_tags=options.keep_style_tags,
        include_star_selectors=options.include_star_selectors,
        remove_classes=options.remove_classes,
        strip_important=options.strip_important,
        external_styles=options.external_styles,
        css_text=options.css_text,
        method=options.method,
        base_path=options.base_path,
        disable_basic_attributes=options.disable_basic_attributes,
        disable_validation=options.disable_validation,
    )
    options.outfile.write(
        p.transform(encoding=options.encoding, pretty_print=options.pretty)
    )
    return 0
235282
def _parse_arguments():
        
        parser = get_base_arguments(get_parser())
        parser = get_tc_arguments(parser)
        args, unknown = parser.parse_known_args()
        return args, unknown
1316136
def add_arguments(cls, subparsers, dirs):
        
        parser = subparsers.add_parser(
            'packet',
            help='Packet Bare Metal',
            formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120))

        m = parser.add_argument_group('Mandatory Packet Parameters') # pylint: disable=invalid-name

        g = m.add_mutually_exclusive_group(required=False) # pylint: disable=invalid-name
        g.add_argument('-create-demand',
                       action='store_true',
                       help='Create an on demand based bare metal device instance.')

        g.add_argument('-create-spot',
                       action='store_true',
                       help='Create a spot price based bare metal device instance.')

        g.add_argument('-reboot',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Reboot active instances.')

        g.add_argument('-stop',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Stop active instances.')

        g.add_argument('-terminate',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Terminate active instances.')

        o = parser.add_argument_group('Optional Parameters') # pylint: disable=invalid-name
        o.add_argument('-create-volume',
                       nargs='+',
                       type=str,
                       metavar='s',
                       help='Create storage: <plan> <size> <region> <description>')

        o.add_argument('-conf',
                       metavar='path',
                       type=argparse.FileType(),
                       default=os.path.join(dirs.user_config_dir, 'examples', 'packet', 'packet.json'),
                       help='Packet configuration')

        o.add_argument('-list-projects',
                       action='store_true',
                       help='List available projects.')

        o.add_argument('-list-plans',
                       action='store_true',
                       help='List available plans.')

        o.add_argument('-list-operating-systems',
                       action='store_true',
                       help='List available operating systems.')

        o.add_argument('-list-spot-prices',
                       action='store_true',
                       help='List spot prices.')

        o.add_argument('-list-facilities',
                       action='store_true',
                       help='List available facilities.')

        o.add_argument('-list-devices',
                       action='store_true',
                       help='List devices under given project name.')

        o.add_argument('-project',
                       metavar='project',
                       type=str,
                       default='fuzzing',
                       help='The project to perform operations on.')
        o.add_argument('-tags',
                       metavar='seq',
                       nargs='+',
                       type=str,
                       help='Tags associated with the instance.')
        o.add_argument('-region',
                       metavar='region',
                       type=str,
                       default='nrt1',
                       help='The facility in which the instance is going to run.')
        o.add_argument('-os',
                       metavar='name',
                       type=str,
                       default='ubuntu_18_04',
                       help='The operating system for the created instance.')
        o.add_argument('-plan',
                       metavar='name',
                       type=str,
                       default='baremetal_0',
                       help='The instance type to run.')
        o.add_argument('-max-spot-price',
                       metavar='#',
                       type=float,
                       default='0.05',
                       help='Max price for spot instances.')
        o.add_argument('-count',
                       metavar='#',
                       type=int,
                       default='1',
                       help='The amount of devices to be spawned.')
        o.add_argument('-only',
                       metavar='k=v',
                       nargs='+',
                       type=str,
                       help='Filter instances by criterias.')
        o.add_argument('-version',
                       action='version',
                       version='%(prog)s {}'.format(cls.VERSION),
                       help=argparse.SUPPRESS)
558954
def _common_parser():
    
    import argparse
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-examples", action="store_true",
                        help="See detailed help and examples for this script.")
    parser.add_argument("-verbose", action="store_true",
                        help="See verbose output as the script runs.")
    parser.add_argument('-action', nargs=1, choices=['save','print'], default='print',
                        help="Specify what to do with the output (print or save)")
    parser.add_argument("-debug", action="store_true",
                        help="Print verbose calculation information for debugging.")

    return parser
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
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
593141
def add_arguments(self, parser):
        
        group = parser.add_mutually_exclusive_group(required=True)
        group.add_argument('-l', '--list', nargs='?',
                           type=str.lower, default='_',
                           choices=['usb', 'ip'],
                           help='list all the connected emulators')
        group.add_argument('-s', '--supported', nargs=1,
                           help='query whether a device is supported')
        group.add_argument('-t', '--test', action='store_true',
                           help='perform a self-test')
        return None
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)
812609
def create_parser():
    
    parser = argparse.ArgumentParser(prog=pylink.__title__,
                                     description=pylink.__description__,
                                     epilog=pylink.__copyright__)
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + pylink.__version__)
    parser.add_argument('-v', '--verbose', action='count', default=0,
                        help='increase output verbosity')

    kwargs = {}
    kwargs['title'] = 'command'
    kwargs['description'] = 'specify subcommand to run'
    kwargs['help'] = 'subcommands'
    subparsers = parser.add_subparsers(**kwargs)

    for command in commands():
        kwargs = {}
        kwargs['name'] = command.name
        kwargs['description'] = command.description
        kwargs['help'] = command.help
        subparser = subparsers.add_parser(**kwargs)
        subparser.set_defaults(command=command.run)
        command.add_arguments(subparser)

    return parser