2

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.

2
  • 1
    I guess you could read z and get it out of the way, then read the rest of arguments in order (stackoverflow.com/questions/9027028/argparse-argument-order) and error out if their number is odd. Commented Jul 2, 2013 at 4:53
  • 2
    you should be able to read the rest using 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 with nargs=1 check stackoverflow.com/questions/13174975/… for the choice on nargs Commented Jul 2, 2013 at 4:58

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I combined that with a slight hack to parse the 'a' 'b' combinations and now errors are handled gracefully.
0
import sys

def main(args):
    print args[0]
    print len(args)
    print [arg for arg in args]

if __name__ == '__main__':
    main(sys.argv)

1 Comment

Thank you for the suggestion, I would like to stick with argparse if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.