Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to handle invalid arguments with argparse in Python?

I use argparse to parse command line arguments and by default on receiving invalid arguments it prints help message and exits. 

#foo.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()

 How to catch this exception when it receives invalid arguments?


1 Answer
Rajendra Dharmkar

We rewrite given code as follows

#foo.py
import argparse
class InvalidArgError(Exception):pass
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
try:
print (args.echo)
raise InvalidArgError
except InvalidArgError as e:
print e

When this script is run at the terminal as follows

$ python foo.py echo bar

We get the following output

usage: foo.py [-h] echo
foo.py: error: unrecognized arguments: bar


Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.