Set constant for arg parse when using nargs '*'

Question:

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 -e p it should print ‘p’
and python test.py -e p q it should print ‘p’ and ‘q’

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

Asked By: vegiv

||

Answers:

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")
Answered By: Olvin Roght