metavar=('timestamp', 'tolerance')
usage: foo.py [-h] [-t timestamp [tolerance ...]]
,因此可以命名两个值。,但是,帮助消息仍然看起来像这样:
-t
[-t timestamp [tolerance]]
可以接受两个以上的论点。
我怎么能说
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--timestamp', nargs='+', metavar=('timestamp', 'tolerance'))
args = parser.parse_args()
if args.timestamp and len(args.timestamp) > 2:
sys.exit('Argument --timestamp takes one or two values')
?我的实际代码如下:import argparse
import re as _re
class CustomParser(argparse.ArgumentParser):
def _match_argument(self, action, arg_strings_pattern):
if action.dest == 'name':
# Account for flexible number of arguments. The pattern is copied from the parent class'
# _get_nargs_pattern() function.
narg_pattern = '(-*A{1,2})'
match = _re.match(narg_pattern , arg_strings_pattern)
if match:
return len(match.group(1))
else:
raise argparse.ArgumentError(action, "expected {} or {} arguments".format(1, 2))
else:
return super()._match_argument(action, arg_strings_pattern)
if __name__ == '__main__':
parser = CustomParser("Flexible argument number test")
# nargs must be 2 so that the help output properly formats the metavar argument.
# Notice that I added '[]' around the optional argument to be consistent with argparse.
parser.add_argument("--name", nargs=2, metavar=("FIRST", "[LAST]"),
help="Your name: FIRST LAST. The last name is optional.")
args = parser.parse_args()
print(args)
我意识到我真的很晚才参加聚会,但是我必须为一个工作项目完成同样的事情。以下是我所做的简单的版本。 Fulll披露:
这显然是hacky的,因为它依赖于私人功能;这是我看到这样做的唯一方法,因为似乎没有支持支持。我的解决方案是包装的一部分,该应用程序包含我需要的特定版本的Python(3.x)(当我访问私人API来完成此操作时),并且我的项目具有重大的自动测试,以便将来捕获任何破裂。您已经被警告了。
SCRIPT --help
usage: Flexible argument number test [-h] [--name FIRST [LAST]]
optional arguments:
-h, --help show this help message and exit
--name FIRST [LAST] Your name: FIRST LAST. The last name is optional.
SCRIPT --name John
Namespace(name=['John'])
SCRIPT --name John Smith
Namespace(name=['John', 'Smith'])
SCRIPT --name
usage: Flexible argument number test [-h] [--name FIRST [LAST]]
Flexible argument number test: error: argument --name: expected 1 or 2 arguments
示例输出:
显然有些事情您可能想解决的问题,例如:
参数化您要寻找的选项的名称,以使“名称”值不重复
具有参数数量可以变化和查找参数的参数词典,而不是只有一个仅适用于单个参数的if statement。我的方法是创建一个划分值的函数。如果有2个以上的值,或小于1,则抛出一个
argparse
,因此可以代表我抱怨。我还使用名称空间来命名邮票和容忍度,使呼叫者变得容易。
#!/usr/bin/env python3
import argparse
def stamp_and_tolerance(value=None):
if value is None:
return argparse.Namespace(stamp=None, tolerance=None)
tokens = value.split(",")
if len(tokens) == 1:
return argparse.Namespace(stamp=tokens[0], tolerance=None)
elif len(tokens) == 2:
return argparse.Namespace(stamp=tokens[0], tolerance=tokens[1])
raise ValueError()
parser = argparse.ArgumentParser()
parser.add_argument(
"-t",
"--timestamp",
type=stamp_and_tolerance,
default=stamp_and_tolerance(),
metavar="stamp[,tolerance]",
help="Timestamp and optional tolerance",
)
args = parser.parse_args()
print(f"Stamp: {args.timestamp.stamp}")
print(f"Tolerance: {args.timestamp.tolerance}")
./my.py -h
usage: my.py [-h] [-t stamp[,tolerance]]
options:
-h, --help show this help message and exit
-t stamp[,tolerance], --timestamp stamp[,tolerance]
Timestamp and optional tolerance
./my.py
Stamp: None
Tolerance: None
./my.py -t mystamp
Stamp: mystamp
Tolerance: None
./my.py -t mystamp,mytolerance
Stamp: mystamp
Tolerance: mytolerance
我设置了默认值,这样我就不必打扰
if args.timestamp != None
我使用SimpleNamespace
,因此命名参数,使访问更好