with argparse, is it possible to check whether the first positional argument has been entered:
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("object_type", type=str)
parser.add_argument("--pass1", type=str)
parser.add_argument("--pass2", type=str)
args = parser.parse_args()
print(args)
when calling: myscript.py --pass1=foo, I get the error: error: the following arguments are required: object_type
what makes sense, but there don't seem to be a way to catch the error beforehand.
Something like:
if args.object_type is None:
raise argparse.ArgumentError(message="object_type must be defined!")
tried also with try/except with no luck.
possible or not ?
sys.exit(2)fromargparseitself and there's no way to catch that... probably.nargs='?'to the positionaladd_argument. Then, you'll need to check using some other meansparser.errorandparser.exitmethods to capture an error., keeping it from exiting. There is also anexit_on_errorparameter, but that may not work with this error, since it isn't redirecting aArgumentErrorincident.