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 parse_args()
method allows abbreviations of long arguments to be written. It infers which argument is being indicated through the abbreviation. For instance, if a user wants to supply a value for an argument radius
with a long option string as --radius
, they will write --radius 20
. Using abbreviations, they can write --rad 20
.
However, an abbreviation can match more than one argument. In that case, the program throws an error.
The allow_abbrev
parameter supplied to the add_argument()
function can turn this option off, and any attempt at using abbreviations will throw an error.
The following examples demonstrate how to use abbreviated supply values for arguments and turn this feature off.
The following program uses the abbreviations --f
and --rd
for the arguments --foo
and --radius
, respectively. The program infers what arguments the values belong to, as illustrated:
import argparse#create an ArgumentParser objectparser = argparse.ArgumentParser(description = 'Calculate radius of the circle')#declare argumentsparser.add_argument('--foo')parser.add_argument('--radius', type = int, help='radius of the circle')args = parser.parse_args('--f bar --rd 30'.split())print(args)
The following program uses the abbreviations --f
and --rd
for the arguments --foo
and --radius
, respectively. However, the abbreviations are disabled, so the program throws an error, as seen here:
import argparse#create an ArgumentParser objectparser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)#declare argumentsparser.add_argument('--foo')parser.add_argument('--radius', type = int, help='radius of the circle')args = parser.parse_args('--f bar --rd 30'.split())print(args)
Free Resources