简体   繁体   中英

argparse - python

In a python script I want to have three positional arguments and two optional arguments(including 'help'). So my need is like following

Correct:

./myscript.py ONE TWO THREE
./myscript.py --list

Incorrect:

./myscript.py ONE TWO THREE --list

I want to make all positional argument and the optional argument as mutual exclusive using argparse itself.

This approxmates what you want:

class Three(argparse.Action):
    # custom action that requires 0 or 3 values
    def __call__(self,parser,namespace,values,option_string):
        if len(values) in [0,3]:
            setattr(namespace, self.dest, values)
        else:
            raise argparse.ArgumentError(self,'must have 3 values')

custom = 'usage: %(prog)s [-h] (--list | ONE TWO THREE)'
p=argparse.ArgumentParser(prog='PROG',usage=custom)
g=p.add_mutually_exclusive_group(required=True)
g.add_argument('--list',action='store_true')
g.add_argument('pos',nargs='*',default=[],action=Three)

It raises an error if both --list and pos are given, if nothing is given, or the number of pos values is not 3. I included a custom usage since the default is:

usage: PROG [-h] (--list | pos [pos ...])

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