The argparse
module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.
The parse_args()
function of the ArgumentParser
class parses arguments and the add_argument()
function adds arguments to be accepted from the user.
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.
The following code demonstrates how to use the default_argument
argument.
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 program’s output illustrates that an empty object is returned when arguments are provided to the parse_args()
function.
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser(argument_default = argparse.SUPPRESS)# add argumentsparser.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)
Free Resources