5

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 4

8

You could use contextlib.redirect_stderr to suppress the output from argparse:

import io
from contextlib import redirect_stderr

try:
    f = io.StringIO()
    with redirect_stderr(f):
        parser.parse_args()
except:
    print("Invalid arguments or number of arguments")
    exit(2)

Another option is to subclass ArgumentParser and override the exit method.

Sign up to request clarification or add additional context in comments.

Comments

4

ArgumentParser.parse_known_args(args=None, namespace=None) might help. It parses the command line and returns a tuple (namespace, unknown_args). namespace contains the args that were recognized and unknown_args is a list of args that weren't recognized.

ns, unknown_args = parser.parse_known_args()
if unknown_args != []:
    # do something with erroneous args, e.g., silent exit

else:
    # do something else

Comments

3

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')

Comments

-1
#!/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!')

1 Comment

The question was how to suppress the error messages that argparse forces upon the user, not how to reformat the arguments so that the message is not thrown.

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.