Skip to content Skip to sidebar Skip to footer

Python Argparse Skip If Not Int

I would like to have 3 optional positional arguments (int, int, then str). What I want: $ ./args.py 0 100 vid start=0 end=100 video='vid' $ ./args.py 0 100 start=0 end=100 video=N

Solution 1:

There is no built-in way to do this cleanly, I think. Thus, you'll just have to gather all of the options into a list and parse them out yourself.

e.g.

parser.add_argument('start_end_video', nargs='*')
args=parser.parse_args()
iflen(args.start_end_video) == 1:
   video = args.start_end_video
elif len(args.start_end_video) == 3:
   start, end, video = args.start_end_video

etc.

Solution 2:

I think you should add what your arguments are called:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', '--start', type=int)
parser.add_argument('-e', '--end', type=int)
parser.add_argument('-v', '--video', type=str)

args = parser.parse_args()
for arg invars(args):
    print(arg, '=', getattr(args, arg))

That way you can specify the arguments and no confusion can occur:

$ ./args.py -s 0-e 100-v vid
start=0end=100
video = vid
$ ./args.py -s 0-e 100start=0end=100
video =None
$ ./args.py -s 0start=0end=None
video =None
$ ./args.py -v vid
start=Noneend=None
video = vid
$ ./args.py
start=Noneend=None
video =None
$ ./args.py vid
usage: args.py [-h] [-s START] [-e END] [-v VIDEO]
args.py: error: unrecognized arguments: vid

Note: I have included short aliases in the arguments above. E.g. You can call -s instead of --start.

Post a Comment for "Python Argparse Skip If Not Int"