argparse is a Python module that streamlines command-line interfaces by providing automation and easy usability. The program implementation defines what arguments it requires, and argparse parses the arguments out of sys.argv. The module also generates help, errors, and usage messages in case a user provides invalid arguments.
First, we create an ArgumentParser object:
parser = argparse.ArgumentParser(description='Process some integers.')
The parser object in the above example will be responsible for parsing the command line arguments into Python data types.
To parse program arguments, we call the parse_argument method of the parser object. We first add arguments in the parser through the add_argument call. Generally, these calls instruct the parser object on transforming the string input on the command line into objects. The information stored in the parser object is used when parse_args is called.
parse__args(args=None, namespace=None)
args is the list of strings to parse. It is taken by default from sys.argv.namespace is the object in which attributes are stored. By default, it is a new empty Namespace object.The function returns a Namespace object.
To demonstrate the use of the parse_args method, we would first add some arguments through the add_argument method of the parser object.
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))
When we call the parse_args method, it will return a Namespace object with two attributes, integers and accumulate. The method inspects the command line, converts each argument to its type, and performs the appropriate action. The integers attribute will be a list of ints, and the accumulate attribute is the function that is executed on the list. If --sum was specified in the command line, then the sum function is executed, else max is executed by default.
If we input the following command on the command line:
python prog.py 1 2 3 4
Then, according to the program, max is stored in args.accumulate, and the program returns 4 as the output.
Similarly, if we input the following command on the command line:
python prog.py 1 2 3 4 --sum
Then, according to the program, sum is stored in args.accumulate, and the program returns 10 as the output.
Free Resources