简体   繁体   中英

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

I want to be able to call foo.py -R ab -R cd -R ef and get something like [('a', 'b'), ('c', 'd'), ('e', 'f')] in a variable. I can instead use foo.py -R a=b -R c=d -R e=f and do the splitting manually, but I'd rather not do this, because I'm building a wrapper around another program and would like to mimic it's command line option input format.

I have tried the 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 then I get ['e', 'f'] when I call it as foo.py -R ab -R cd -R ef .

You can use a 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 is 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 a b -R c d -R e f".split())

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM