Suppressing argparse Error message - Python

Viewed 2247

I'm using argparse to parse command line arguments. However at this time, I have an unusual request: I want to suppress the error message. For example:

 # !/usr/bin/env python
 try:
        parser = argparse.ArgumentParser(description='Parse')
        parser.add_argument('url', metavar='URL', type=str, nargs='+', 
                            help='Specify URL')
 except:
        print("Invalid arguments or number of arguments")
        exit(2)

so I only expect that to print "Invalid arguments or number of arguments" and nothing else. However, then I execute the code for example:

./foo --BOGUS

I'm getting the full usage message:

usage: foo [-h]
foo: error: too few arguments
foo: Invalid arguments or number of arguments 

How can I achieve that?

4 Answers

As of Python 3.9, use the exit_on_error parameter:

parser = argparse.ArgumentParser(exit_on_error=False)

This allows you to catch errors manually:

try:
    parser.parse_args('--integers a'.split())
except argparse.ArgumentError:
    print('Catching an argumentError')
#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser()
url_command = parser.add_argument('url', metavar='URL', nargs='*', help='Specify URL(s)')
args = parser.parse_args()

url_command.nargs='+'  # format the usage correctly
if not args.url:
    parser.error('At least one URL is required!')
Related