简体   繁体   中英

Set constant for arg parse when using nargs '*'

I have a setup like this. What I want to do is to send a constant value if only the -e/--exp are sent, and if -p/--plot are sent then it should only do the plotting. So a default value will not work, as it then will print 'do everything'.

def run(args):
    if args.exp:
        if 'p' in args.exp:
           print('p')
        if 'q' in args.exp:
           print('q')
        if 't' in args.exp:
           print('t')
        else:
            print('do everything')
    if args.plot:
        if 'p' in args.plot:
           print('plot p')
        if 'q' in args.plot:
           print('plot q')
        if 't' in args.plot:
           print('plot t')
        else:
            print('plot everything')
if __name__=="__main__":
    parser = argparse.ArgumentParser(
        prog="test.py")
    parser.add_argument('-e', '--exp', nargs='*',
                         help='pass p, q , t or nothing')
    parser.add_argument('-p', '--plot', nargs='*',
                         help='pass p, q , t or nothing')
    args = parser.parse_args()
    run(args=args)

So basically what I want is to have it like this.

if __name__=="__main__":
    parser = argparse.ArgumentParser(
        prog="test.py")
    parser.add_argument('-e', '--exp', nargs='*', const='a'
                         help='pass p, q , t or nothing')

so that if I run python test.py -e it should print 'do everything' And if i run python test.py -p it should print 'plot everything' if run python test.py -ep it should print 'p' and python test.py -epq it should print 'p' and 'q'

Is this possible without writing a custom action as nargs='*' does not support const value

Basically you just need to use choices argument. Also I'd suggest you to use mutually exclusive group to avoid both -e and -p modes.

from argparse import ArgumentParser

parser = ArgumentParser()
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("-e", "--exp", nargs="*", choices=("p", "q", "t"))
mode.add_argument("-p", "--plot", nargs="*", choices=("p", "q", "t"))
args = parser.parse_args()

if args.exp is None:
    if args.plot:
        print(*args.plot)
    else:
        print("plot everything")
else:
    if args.exp:
        print(*args.exp)
    else:
        print("do everything")

You can help my country, check my profile info .

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