使用argparse
,我希望用户指定 6 个值作为一个可选输入参数的参数。是否有内置方法来检查这些值是否为浮点数?
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
help="my help message",
default=None)
使用type=float
:
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
help="my help message", type=float,
default=None)
演示:
>>> import argparse
>>> parser = argparse.ArgumentParser(description='Process some floats.')
>>> parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
... help="my help message", type=float,
... default=None)
_StoreAction(option_strings=['-e'], dest='e', nargs=6, const=None, default=None, type=<type 'float'>, choices=None, help='my help message', metavar=('a', 'b', 'c', 'd', 'e', 'f'))
>>> try:
... parser.parse_args('-e 1.0 2.0 3.33 4.45 5.15 6.0'.split())
... except SystemExit:
... pass
...
Namespace(e=[1.0, 2.0, 3.33, 4.45, 5.15, 6.0])
>>> try:
... parser.parse_args('-e foo bar baz spam ham eggs'.split())
... except SystemExit:
... pass
...
usage: [-h] [-e a b c d e f]
: error: argument -e: invalid float value: 'foo'