Issue
How can I specify a minimum or maximum floating point argument using argprase
? I'd like to be able to provide a command-line argument between a min and max floating point value.
The closest thing I can find is the choices
option in add_argument()
, but that only specifies allowable values for the argument.
parser.add_argument("L", type=float, choices=range(2))
The command-line argument 0.5
for L fails:
invalid choice: 0.5 (choose from 0, 1)
Solution
You can (and should) use a custom type function. It's much more user friendly.
def range_limited_float_type(arg):
""" Type function for argparse - a float within some predefined bounds """
try:
f = float(arg)
except ValueError:
raise argparse.ArgumentTypeError("Must be a floating point number")
if f < MIN_VAL or f > MAX_VAL:
raise argparse.ArgumentTypeError("Argument must be < " + str(MAX_VAL) + "and > " + str(MIN_VAL))
return f
parser.add_argument(
'-f',
'--float',
type=range_limited_float_type,
help='Your argument description'
)
Answered By - rdas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.