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.
Most arguments are specified through the prefix -
. For instance, the value of an argument foo
may be specified as --foo
or -f
, depending on how the user has defined the argument in the add_argument()
function. The user can supply a set of prefixes to the prefix_chars
argument of the ArgumentParser
object to support additional prefixes.
The following program demonstrates how to use the different prefixes when handling arguments.
The program sets the prefix_chars
value to -+/
, which means the +
, /
, and -
characters can be used as prefixes.
The program then creates arguments with each of the three prefixes and parses the provided values for the arguments.
The default value of
prefix_chars
is-
. If the specified value ofprefix_chars
does not contain-
, then using-
as a prefix will raise an error.
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser(description = 'Calculate radius of the circle', prefix_chars = '-+/')# add argumentsparser.add_argument('-r','--radius', type = int)parser.add_argument('+x', type = int)parser.add_argument('/y', type = int)args = parser.parse_args('-r 10 +x 6 /y 3'.split())print(args)
Free Resources