Python argparse.py() Examples

The following are 6 code examples of argparse.py(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: registry.py    From fairseq with 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
Source File: scripts.py    From ray with 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
Source File: scripts.py    From ray with 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
Source File: registry.py    From attn2d with 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
Source File: command.py    From sdb with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 args: Optional[List[str]] = None,
                 name: str = "_") -> None:
        self.name = name
        self.isfirst = False
        self.islast = False

        self.parser = type(self)._init_parser(name)

        #
        # The if-else clauses below may seem like it can be avoided by:
        #
        #     [1] Passing the `args` function argument to parse_args() even if
        #         it is None - the call won't blow up.
        #
        #  or [2] Setting the default value of `args` to be [] instead of None.
        #
        # Solution [1] doesn't work because parse_args() actually distinguishes
        # between None and [] as parameters. If [] is passed it returns an
        # argparse.Namespace() with default values for all the fields that the
        # command specified in _init_parser(), which is what we want. If None
        # is passed then argparse's default logic is to attempt to parse
        # `_sys.argv[1:]` (reference code: cpython/Lib/argparse.py) which is
        # the arguments passed to the sdb from the shell. This is far from what
        # we want.
        #
        # Solution 2 is dangerous as default arguments in Python are mutable(!)
        # and thus invoking a Command with arguments that doesn't specify the
        # __init__() method can pass its arguments to a similar Command later
        # in the pipeline even if the latter Command didn't specify any args.
        # [docs.python-guide.org/writing/gotchas/#mutable-default-arguments]
        #
        # We still want to set self.args to an argparse.Namespace() with the
        # fields specific to our self.parser, thus we are forced to call
        # parse_args([]) for it, even if `args` is None. This way commands
        # using arguments can always do self.args.<expected field> without
        # having to check whether this field exist every time.
        #
        if args is None:
            args = []
        self.args = self.parser.parse_args(args) 
Example #6
Source File: argparse_util.py    From tensorboard with 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