suppressing argparse error message - python

  • Last Update :
  • Techknowledgy :

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)

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

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

Suggestion : 2

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.,Create a mutually exclusive group. argparse will make sure that only one of the arguments in the mutually exclusive group was present on the command line:,Sometimes it may be useful to have an ArgumentParser parse arguments other than those of sys.argv. This can be accomplished by passing a list of strings to parse_args(). This is useful for testing at the interactive prompt:,'help' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created.

import argparse

parser = argparse.ArgumentParser(description = 'Process some integers.')
parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
   help = 'an integer for the accumulator')
parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
   const = sum,
   default = max,
   help = 'sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
$ python prog.py - h
usage: prog.py[-h][--sum] N[N...]

Process some integers.

positional arguments:
   N an integer
for the accumulator

options:
   -h, --help show this help message and exit
   --sum sum the integers(
      default: find the max)
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4--sum
10
$ python prog.py a b c
usage: prog.py[-h][--sum] N[N...]
prog.py: error: argument N: invalid int value: 'a'
>>> parser = argparse.ArgumentParser(description = 'Process some integers.')
>>> parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
      ...help = 'an integer for the accumulator') >>>
   parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
      ...
      const = sum,
      default = max,
      ...help = 'sum the integers (default: find the max)')

Suggestion : 3

I'm using argparse to parse command line anycodings_arguments arguments. However at this time, I have an anycodings_arguments unusual request: I want to suppress the anycodings_arguments error message. For example:,You could use contextlib.redirect_stderr anycodings_command-line to suppress the output from argparse:,Another option is to subclass anycodings_command-line ArgumentParser and override the exit anycodings_command-line method.,As of Python 3.9, use the exit_on_error anycodings_command-line parameter:

I'm using argparse to parse command line anycodings_arguments arguments. However at this time, I have an anycodings_arguments unusual request: I want to suppress the anycodings_arguments 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 anycodings_arguments arguments or number of arguments" and anycodings_arguments nothing else. However, then I execute the anycodings_arguments 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

You could use contextlib.redirect_stderr anycodings_command-line 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)

ArgumentParser.parse_known_args(args=None, anycodings_command-line namespace=None) might help. It parses anycodings_command-line the command line and returns a tuple anycodings_command-line (namespace, unknown_args). namespace anycodings_command-line contains the args that were recognized anycodings_command-line and unknown_args is a list of args that anycodings_command-line 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

As of Python 3.9, use the exit_on_error anycodings_command-line parameter:

parser = argparse.ArgumentParser(exit_on_error = False)

This allows you to catch errors anycodings_command-line 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!')

Suggestion : 4

You can create parser error messages according to your script needs. This is through the argparse.ArgumentParser.error function. The below example shows the script printing a usage and an error message to stderr when --foo is given but not --bar., Custom parser error message with argparse , Custom parser error message with argparse ,Assuming your script name is sample.py, and we run: python sample.py --foo ds_in_fridge

You can create parser error messages according to your script needs. This is through the argparse.ArgumentParser.error function. The below example shows the script printing a usage and an error message to stderr when --foo is given but not --bar.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--foo")
parser.add_argument("-b", "--bar")
args = parser.parse_args()
if args.foo and args.bar is None:
   parser.error("--foo requires --bar. You did not specify bar.")

print "foo =", args.foo
print "bar =", args.bar

The script will complain with the following:

usage: sample.py[-h][-f FOO][-b BAR]
sample.py: error: --foo requires--bar.You did not specify bar.

Suggestion : 5

Assuming the Python code above is saved into a file called prog.py, it can be run at the command line and provides useful help messages:,If invalid arguments are passed in, it will issue an error:,Print a help message, including the program usage and information about the arguments registered with the ArgumentParser. If file is None, sys.stdout is assumed.,If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

import argparse

parser = argparse.ArgumentParser(description = 'Process some integers.')
parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
   help = 'an integer for the accumulator')
parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
   const = sum,
   default = max,
   help = 'sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
$ python prog.py - h
usage: prog.py[-h][--sum] N[N...]

Process some integers.

positional arguments:
   N an integer
for the accumulator

optional arguments:
   -h, --help show this help message and exit
   --sum sum the integers(
      default: find the max)
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4--sum
10
$ python prog.py a b c
usage: prog.py[-h][--sum] N[N...]
prog.py: error: argument N: invalid int value: 'a'
>>> parser = argparse.ArgumentParser(description = 'Process some integers.')
>>> parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
      ...help = 'an integer for the accumulator') >>>
   parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
      ...
      const = sum,
      default = max,
      ...help = 'sum the integers (default: find the max)')

Suggestion : 6

The program provides the parser with three arguments, r, x, and foo. It also sets the default_argument to argparse.SUPPRESS. This means that the program will halt attribute creation if no values are provided for the arguments.,The following code demonstrates how to use the default_argument argument.,The program’s output illustrates that an empty object is returned when arguments are provided to the parse_args() function.,The user often supplies a default value of an argument in case a value is not specified. To provide a global, parser-wide default value for arguments, the argument_default attribute is used.

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(argument_default = argparse.SUPPRESS)
# add arguments
parser.add_argument('-r', type = int)
parser.add_argument('x', nargs = '?', )
parser.add_argument('--foo', type = int)
args = parser.parse_args('-r 2 5 --foo 5'.split())
print(args)
args = parser.parse_args(''.split())
print(args)