0

I have a script which basically asks the user for the argument to be passed to the program as below:

parser = argparse.ArgumentParser()
parser.add_argument("-t" , required = True)
args , unknown = parser.parse_known_args()

#rest of the code

Now I wanna do error handling so it shows the message I want and run the functions I want in case the user didn't enter the argument or entered it incorrectly. I have tried putting everything in try and except however I couldn't find the proper error type to do it for me

try: 
  parser = argparse.ArgumentParser()
  parser.add_argument("-t" , required = True)
  args , unknown = parser.parse_known_args()

  #rest of the code
except argparse.ArgumentError:
   myfunc()

However, this way if I get any other errors in my code, it still caught here and not in their own try and except.

NateR
  • 85
  • 9

2 Answers2

1

Argparse raises a SystemExit when a required argument is missing. You could use the else clause in the try/except to execute the rest of your code only if the arguments were parsed correctly:

try: 
    parser = argparse.ArgumentParser()
    parser.add_argument("-t" , required = True)
    args , unknown = parser.parse_known_args()
except SystemExit:
    func_for_wrong_args()
else:
    func_for_correct_args()
Matteo Zanoni
  • 3,429
  • 9
  • 27
0

Use assert, it comes with a print message.

assert args.t, "Argument --t is required"