[Python] Detailed explanation of argparse module

Detailed explanation of Python argparse module

argparse is a Python library for parsing command-line arguments, which is part of the Python standard library. stdlib code based on python 2.7. The argparse module makes it easy to write user-friendly command-line interfaces. The program defines the required arguments, and argparse will figure out how to parse them from sys.argv. The argparse module also automatically generates help and usage messages, and issues errors when the user supplies invalid arguments to the program.

Simple implementation of the calculation of the volume of a cylinder

In order to facilitate the understanding of the argparse command line parameter parsing module, we start with a simple program:

import math


def cylinder_volume(radius, height):
    vol = (math.pi) * (radius ** 2) * height
    return vol


if __name__ == '__main__':
    print(cylinder_volume(2, 4))

Execute the code through PyCharm, the result displayed:

insert image description here

Execute the code through the command line, and the displayed result:

insert image description here

You can see that if you use the command line method, you need to enter the file directory where the xxx.py file to be executed is located, and enter python xxx.py.

Using the argparse module to calculate the volume of a cylinder

  1. import argparse module

    import argparse
    
  2. Create a parsing object parser

    parser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
    

    Among them, the parser parsing object is equivalent to a container for loading parameters, and description is used to describe the parsing object.

  3. Add command line parameters

    parser.add_argument('radius', type=int, help='Radius of Cylinder')
    parser.add_argument('height', type=int, help='Height of Cylinder')
    args = parser.parse_args()
    

    In the example of calculating the volume of a cylinder, the required parameters are radius and height, so these two parameters need to be added to the analysis object. The type of the parameter is defined as int type, and help is used to describe the parameter. .

  4. Replace the original function arguments with command-line arguments

    print(cylinder_volume(args.radius, args.height))
    
  5. Complete code reproduction

    import math
    import argparse
    
    parser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
    parser.add_argument('radius', type=int, help='Radius of Cylinder')
    parser.add_argument('height', type=int, help='Height of Cylinder')
    args = parser.parse_args()
    
    
    def cylinder_volume(radius, height):
        vol = (math.pi) * (radius ** 2) * height
        return vol
    
    
    if __name__ == '__main__':
        print(cylinder_volume(args.radius, args.height))
    
  6. execute code

    Execute the code directly in PyCharm, and the result shows:

insert image description here

PyCharm will report an error directly, because this code needs to pass in parameters.

Now execute the code through the command line, and the result shows:

insert image description here

It can be seen that the result is the same as before.

Next, we can call the --help or -h parameter to view the description of the program:

insert image description here

Now, we try to change the order of the previously passed parameters, and the results are as follows:

insert image description here

It can be seen that the result is completely different. From the prompt information in the help, we know that the parameters passed in need to be carried out in strict order. However, in daily life, there may be a large number of parameters involved, and the order of parameters is not so good. Memory, at this time we can modify the original code to enable it to use optional parameters:

parser.add_argument('-r', '--radius', type=int, help='Radius of Cylinder')
parser.add_argument('-H', '--height', type=int, help='Height of Cylinder')

It should be noted here that since the '-h' parameter has been occupied by the help command, we use '-H' for height.

The following is the display result of executing the code again:

insert image description here

Now, we pass '-h' to view the description of the program:
insert image description here

If you want to make the above description look more concise, you can modify the code:

parser.add_argument('-r', '--radius', type=int, metavar='', help='Radius of Cylinder')
parser.add_argument('-H', '--height', type=int, metavar='', help='Height of Cylinder')

Now, we pass '-h' again to see the effect:

insert image description here

So now if only one parameter is entered, what will happen to the result?

insert image description here

You can see that in the error message, the parameter that does not specify a specific value will be assigned a value of None. To avoid this situation, we can modify the code as follows:

parser.add_argument('-r', '--radius', type=int, metavar='', required=True, help='Radius of Cylinder')
parser.add_argument('-H', '--height', type=int, metavar='', required=True, help='Height of Cylinder')

Now do it again:

insert image description here

You can see that the parameters that need to be added will be prompted at this time.

Introduction to Mutual Exclusion Parameters

Now we try to add the mutex group:

group = parser.add_mutually_exclusive_group()
group.add_argument('-q', '--quiet', action='store_true', help='print quiet')
group.add_argument('-v', '--verbose', action='store_true', help='print verbose')

First create a group container, and then add parameters to it. Assigning the action parameter to 'store_true' means that when adding '-q' or '--quiet' ('-v' or '--verbose') to the command, the program will Assigns true to args.quiet, which is false by default. Then using this principle, we can modify the content of the main function:

volume = cylinder_volume(args.radius, args.height)
    if args.quiet:
        print("quiet: %s" % volume)
    elif args.verbose:
        print("verbose: %s" % volume)
    else:
        print("Volume of a Cylinder with radius %s and height %s is %s" % (args.radius, args.height, volume))

Now run a command line test to see the effect:

insert image description here
It should be noted that the meaning of mutual exclusion refers to the parameters that cannot participate in the mutual exclusion group at the same time, that is, only one parameter can be established. If more than two parameters in the mutual exclusion group are forcibly passed in, the following error message will appear:

insert image description here

Full version improved code

import math
import argparse

parser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
parser.add_argument('-r', '--radius', type=int, metavar='', required=True, help='Radius of Cylinder')
parser.add_argument('-H', '--height', type=int, metavar='', required=True, help='Height of Cylinder')
group = parser.add_mutually_exclusive_group()
group.add_argument('-q', '--quiet', action='store_true', help='print quiet')
group.add_argument('-v', '--verbose', action='store_true', help='print verbose')
args = parser.parse_args()


def cylinder_volume(radius, height):
    vol = (math.pi) * (radius ** 2) * height
    return vol


if __name__ == '__main__':
    volume = cylinder_volume(args.radius, args.height)
    if args.quiet:
        print("quiet: %s" % volume)
    elif args.verbose:
        print("verbose: %s" % volume)
    else:
        print("Volume of a Cylinder with radius %s and height %s is %s" % (args.radius, args.height, volume))

Guess you like

Origin blog.csdn.net/zzy_NIC/article/details/119821493