Using argparse, I would like the user to specify 6 values as the argument of one optional input argument. Is there a built-in way to check if those values are floats?
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
                        help="my help message",
                        default=None)
                Use type=float:
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
                        help="my help message", type=float,
                        default=None)
Demo:
>>> 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'
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With