Python argparse.py() Examples

The following are code examples for showing how to use argparse.py(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fairseq   Author: pytorch   File: registry.py    MIT License 6 votes vote down vote up
def set_defaults(args, cls):
    """Helper to set default arguments based on *add_args*."""
    if not hasattr(cls, 'add_args'):
        return
    parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, allow_abbrev=False)
    cls.add_args(parser)
    # copied from argparse.py:
    defaults = argparse.Namespace()
    for action in parser._actions:
        if action.dest is not argparse.SUPPRESS:
            if not hasattr(defaults, action.dest):
                if action.default is not argparse.SUPPRESS:
                    setattr(defaults, action.dest, action.default)
    for key, default_value in vars(defaults).items():
        if not hasattr(args, key):
            setattr(args, key, default_value) 
Example 2
Project: ray   Author: ray-project   File: scripts.py    Apache License 2.0 6 votes vote down vote up
def cli():
    parser = argparse.ArgumentParser(
        description="Train or Run an RLlib Agent.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=EXAMPLE_USAGE)
    subcommand_group = parser.add_subparsers(
        help="Commands to train or run an RLlib agent.", dest="command")

    # see _SubParsersAction.add_parser in
    # https://github.com/python/cpython/blob/master/Lib/argparse.py
    train_parser = train.create_parser(
        lambda **kwargs: subcommand_group.add_parser("train", **kwargs))
    rollout_parser = rollout.create_parser(
        lambda **kwargs: subcommand_group.add_parser("rollout", **kwargs))
    options = parser.parse_args()

    if options.command == "train":
        train.run(options, train_parser)
    elif options.command == "rollout":
        rollout.run(options, rollout_parser)
    else:
        parser.print_help() 
Example 3
Project: ray   Author: ray-project   File: scripts.py    Apache License 2.0 6 votes vote down vote up
def cli():
    parser = argparse.ArgumentParser(
        description="Train or Run an RLlib Agent.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=EXAMPLE_USAGE)
    subcommand_group = parser.add_subparsers(
        help="Commands to train or run an RLlib agent.", dest="command")

    # see _SubParsersAction.add_parser in
    # https://github.com/python/cpython/blob/master/Lib/argparse.py
    train_parser = train.create_parser(
        lambda **kwargs: subcommand_group.add_parser("train", **kwargs))
    rollout_parser = rollout.create_parser(
        lambda **kwargs: subcommand_group.add_parser("rollout", **kwargs))
    options = parser.parse_args()

    if options.command == "train":
        train.run(options, train_parser)
    elif options.command == "rollout":
        rollout.run(options, rollout_parser)
    else:
        parser.print_help() 
Example 4
Project: En_francais_si_vous_plait-   Author: lucylow   File: registry.py    MIT License 6 votes vote down vote up
def set_defaults(args, cls):
    """Helper to set default arguments based on *add_args*."""
    if not hasattr(cls, 'add_args'):
        return
    parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, allow_abbrev=False)
    cls.add_args(parser)
    # copied from argparse.py:
    defaults = argparse.Namespace()
    for action in parser._actions:
        if action.dest is not argparse.SUPPRESS:
            if not hasattr(defaults, action.dest):
                if action.default is not argparse.SUPPRESS:
                    setattr(defaults, action.dest, action.default)
    for key, default_value in vars(defaults).items():
        if not hasattr(args, key):
            setattr(args, key, default_value) 
Example 5
Project: tensorboard   Author: tensorflow   File: argparse_util.py    Apache License 2.0 5 votes vote down vote up
def allow_missing_subcommand():
    """Make Python 2.7 behave like Python 3 w.r.t. default subcommands.

    The behavior of argparse was changed [1] [2] in Python 3.3. When a
    parser defines subcommands, it used to be an error for the user to
    invoke the binary without specifying a subcommand. As of Python 3.3,
    this is permitted. This monkey patch backports the new behavior to
    earlier versions of Python.

    This context manager need only be used around `parse_args`; parsers
    may be constructed and configured outside of the context manager.

    [1]: https://github.com/python/cpython/commit/f97c59aaba2d93e48cbc6d25f7ff9f9c87f8d0b2
    [2]: https://bugs.python.org/issue16308
    """

    real_error = argparse.ArgumentParser.error

    # This must exactly match the error message raised by Python 2.7's
    # `argparse` when no subparser is given. This is `argparse.py:1954` at
    # Git tag `v2.7.16`.
    ignored_message = gettext.gettext("too few arguments")

    def error(*args, **kwargs):
        # Expected signature is `error(self, message)`, but we retain more
        # flexibility to be forward-compatible with implementation changes.
        if "message" not in kwargs and len(args) < 2:
            return real_error(*args, **kwargs)
        message = kwargs["message"] if "message" in kwargs else args[1]
        if message == ignored_message:
            return None
        else:
            return real_error(*args, **kwargs)

    argparse.ArgumentParser.error = error
    try:
        yield
    finally:
        argparse.ArgumentParser.error = real_error