I have a long script with several options to be choosen by the user and i was trying to use optparse, but i have read optparse does not accept several inputs in just one option. I mean if i need to calculate the square of certain number, i would like to do it for several and not just for one. I mean to write in the command line, python math.py -i 4 5 6 54 and option -i to be executed over those numbers and returns 16 25 36 2916, and beyond that add more options, like python math.py -i 4 5 6 54 -d 4 5 6 54 and option -d also to be executed over those numbers. Could you help me to know what is the best option to parse?
thanks in advance
Have a look at the following example in the docs.
It uses the callback
option type in optparse. If you are able to, you should probably use argparse
instead but that requires 2.7+.
The example code from the docs:
def vararg_callback(option, opt_str, value, parser):
assert value is None
value = []
def floatable(str):
try:
float(str)
return True
except ValueError:
return False
for arg in parser.rargs:
# stop on --foo like options
if arg[:2] == "--" and len(arg) > 2:
break
# stop on -a, but not on -3 or -3.0
if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
break
value.append(arg)
del parser.rargs[:len(value)]
setattr(parser.values, option.dest, value)
[...]
parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback)
It's a bit hairy but it does more or less what you want while still allowing you to use optparse for other stuff.