本文整理汇总了Python中argparse.py方法的典型用法代码示例。如果您正苦于以下问题:Python argparse.py方法的具体用法?Python argparse.py怎么用?Python argparse.py使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse.py方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_defaults
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import py [as 别名]
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)
示例2: cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import py [as 别名]
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()
示例3: __init__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import py [as 别名]
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)
示例4: allow_missing_subcommand
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import py [as 别名]
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