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=None
$ ./args.py 0
start=0
end=None
video=None
$ ./args.py vid
start=None
end=None
video='vid'
$ ./args.py
start=None
end=None
video=None
What I have tried:
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('start', type=int, nargs='?')
parser.add_argument('end', type=int, nargs='?')
parser.add_argument('video', type=str, nargs='?')
print(parser.parse_args())
The problem with that code is:
$ ./args.py vid
usage: args.py [-h] [start] [end] [video]
args.py: error: argument start: invalid int value: 'vid'
argparse knows that the value 'vid' is not an integer, so I would like it to "skip" the two first arguments start and end since they don't match.
When I make the video argument mandatory, it works a bit better:
parser.add_argument('start', type=int, nargs='?')
parser.add_argument('end', type=int, nargs='?')
parser.add_argument('video', type=str)
Demo:
# Fine!
$ ./args.py 0 100 vid
start=0
end=100
video='vid'
# Fine!
$ ./args.py vid
start=None
end=None
video='vid'
# Not fine
./args.py
usage: args.py [-h] [start] [end] video
args.py: error: the following arguments are required: video
argparseraises an error when thetypedoesn't match; it doesn't skip that argument or go on to try another. Positional values like this are assigned strictly on position, not on value.