0

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 ?

6
  • Yeah, when you fail to give it the required arguments it returns on a sys.exit(2) from argparse itself and there's no way to catch that... probably. Commented May 15, 2024 at 15:42
  • Ok, I found a duplicate question The way to bypass the required positional is to add the kwarg nargs='?' to the positional add_argument. Then, you'll need to check using some other means Commented May 15, 2024 at 15:47
  • Does this answer your question? Argparse optional positional arguments? Commented May 15, 2024 at 15:48
  • actually not, since my positional argument is not optional. Unless positional forcibly means mandatory Commented May 15, 2024 at 16:03
  • The docs talk about changing the parser.error and parser.exit methods to capture an error., keeping it from exiting. There is also an exit_on_error parameter, but that may not work with this error, since it isn't redirecting a ArgumentError incident. Commented May 15, 2024 at 16:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.