deltap
deltap

Reputation: 4206

Parsing command line arguments with argparse

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.

Upvotes: 2

Views: 269

Answers (2)

FMc
FMc

Reputation: 42411

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

Upvotes: 3

Zangetsu
Zangetsu

Reputation: 2015

import sys

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

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

Upvotes: 0

Related Questions