Sunday 15 August 2010

How can I make python's argparse accept any number of [-R a b]s, and aggregate them into a list -



How can I make python's argparse accept any number of [-R a b]s, and aggregate them into a list -

i want able phone call foo.py -r b -r c d -r e f , [('a', 'b'), ('c', 'd'), ('e', 'f')] in variable. can instead utilize foo.py -r a=b -r c=d -r e=f , splitting manually, i'd rather not this, because i'm building wrapper around programme , mimic it's command line alternative input format.

i have tried following:

#!/usr/bin/env python import argparse parser = argparse.argumentparser(description='foo') parser.add_argument('-r', metavar=('a', 'b'), dest='libnames', type=str, default=('.', 'top'), nargs=2) if __name__ == '__main__': args = parser.parse_args() print(args.libnames)

but ['e', 'f'] when phone call foo.py -r b -r c d -r e f.

you can utilize custom argparse.action class.

https://docs.python.org/3/library/argparse.html#argparse.action

import argparse class pairs(argparse.action): def __call__(self, parser, namespace, values, opts, **kwargs): lst = getattr(namespace, self.dest) if lst none: lst = [] setattr(namespace, self.dest, lst) lst.append(tuple(values)) parser = argparse.argumentparser() parser.add_argument('-r', nargs='+', dest='libnames', action=pairs) print parser.parse_args("-r b -r c d -r e f".split())

output:

namespace(libnames=[('a', 'b'), ('c', 'd'), ('e', 'f')])

python argparse

No comments:

Post a Comment