I would like my python program to parse command like arguments like this:
python dosomething.py z a1 b1 a2 b2 ...
where I can have any number of a# b# pairs and z is an unrelated number. If necessary I am OK with specifying the number of a and b pairs.
I'm using argparse.
asked Jul 2, 2013 at 4:45
2 Answers 2
You'll need to define a custom action for such specialized behavior.
import sys
import argparse
class AbsAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if len(values) % 2 == 0:
# If valid, store the values.
setattr(namespace, self.dest, values)
# You could convert the flat list to a list of 2-tuples, if needed:
# zip(values[::2], values[1::2])
else:
# Otherwise, invoke a parser error with a message.
parser.error('abs must be supplied as pairs')
ap = argparse.ArgumentParser()
ap.add_argument('z')
ap.add_argument('abs', nargs = '+', action = AbsAction)
opt = ap.parse_args()
print opt
answered Jul 2, 2013 at 5:14
Sign up to request clarification or add additional context in comments.
1 Comment
deltap
Thanks, I combined that with a slight hack to parse the 'a' 'b' combinations and now errors are handled gracefully.
import sys
def main(args):
print args[0]
print len(args)
print [arg for arg in args]
if __name__ == '__main__':
main(sys.argv)
answered Jul 2, 2013 at 4:53
1 Comment
deltap
Thank you for the suggestion, I would like to stick with argparse if possible.
Explore related questions
See similar questions with these tags.
lang-py
nargs='+'
and then can use a custom action to check for even pairs. and as @deshko mentioned the first positional argument can be specified as z withnargs=1
check stackoverflow.com/questions/13174975/… for the choice on nargs