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-supplied arguments and their values are verified by the parse_arg()
function for errors. If the user supplies ambiguous arguments, invalid types, wrong names, or an incorrect number of arguments, the program exits, and the usage and error are displayed.
The following example demonstrates what some of the invalid argument types are.
The following example provides an invalid value type for the argument -r
:
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser()# add argumentsparser.add_argument('-r', type = int)parser.add_argument('--foo', type = int)args = parser.parse_args('-r abc'.split())print(args)
The following example provides an invalid argument name:
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser()# add argumentsparser.add_argument('-r', type = int)parser.add_argument('--foo', type = int)args = parser.parse_args('--bar'.split())print(args)
The following example provides an invalid number of arguments:
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser()# add argumentsparser.add_argument('r', type = int)parser.add_argument('foo', type = int)args = parser.parse_args('10 8 3'.split())print(args)
Free Resources