Detailed explanation of argparse module

1. Introduction to the 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 those arguments from sys.argv (the command line). The argparse module also automatically generates help and usage messages, and emits errors when the user supplies invalid arguments to the program.

2. Example without using argparse

Generally, terminal commands are not used. For some programs that require variable assignment, we often:

  • 1. Write hard directly in the program (or configuration file).
  • 2. Or use input to enter multiple times on the command line so that it is not easy to debug and modify the operation multiple times. The following is an example:
import math

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

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

argparse

3. Example using argparse

3.1 Simple example of argparse

The main steps to use argparse:

  • Import the argparse package;
  • Create an ArgumentParser() parameter object;
  • Call the add_argument() method to add parameters to the parameter object;
  • Use parse_args() to parse the parameter object of the added parameter to obtain the parsing object; when other parts of the program need to use command line parameters, use parsing object.parameter to obtain.

Here is a simple example:

import math
import argparse  # 1、导入argpase包


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')  # 2、创建参数对象
    parse.add_argument('radius', type=int, help='Radius of Cylinder')  # 3、往参数对象添加参数
    parse.add_argument('height', type=int, help='height of Cylinder')
    args = parse.parse_args()  # 4、解析参数对象获得解析对象
    return args

# 计算圆柱体积
def cal_vol(radius, height):
    vol = math.pi * pow(radius, 2) * height
    return vol


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))  # 5、使用解析对象.参数获取使用命令行参数

Note: Because it is not specified at this time, the command line parameters are assigned in order by default, and different orders will cause different results
insert image description hereinsert image description here

The default command -h can get the help information set when adding parameters
insert image description here

  • Command-line parameter input is assigned in order by default, and different orders will result in different results;
  • The default command -h can get the help information set when adding parameters;

3.2 Advanced example of argparse

add_argument() method (defining how to parse command line parameters):
insert image description here
The parameters are explained as follows:

  • name or flags - A name or list of option strings, eg foo or -f, --foo.

  • action - the action when the command line encounters the parameter, the default value is store.

    • – store_const, indicating that the assignment is const;
    • – append, store the encountered values ​​as a list, that is, if the parameters are repeated, multiple values ​​will be saved;
    • – append_const, which saves a value defined in the parameter specification to a list;
    • – count, stores the number of encounters; in addition, you can also inherit argparse.Action to customize parameter parsing;
  • nargs - the number of command line arguments that should be read, can be

    • A specific number, or a ? number, when a value is not specified, use default for the Positional argument, and use const for the Optional argument
    • Or * sign, indicating 0 or more parameters;
    • Or a + sign means 1 or more parameters.
  • const - the required constant value for action and nargs.

  • default - the default value when no parameter is specified.

  • type - The type the command line argument should be converted to. The default is a string type.

  • choices - A container of allowed values ​​for the parameter.

  • required - Whether optional parameters can be omitted (only for optional parameters).

  • help - the help information of the parameter, when specified as argparse.SUPPRESS means that the help information of the parameter will not be displayed.

  • metavar - the name of the parameter in the usage description, the default is the name of the parameter for the required parameter, and the name of the parameter in all uppercase for the optional parameter.

  • dest - the parsed parameter name, by default the longest name is picked for optional parameters, dashes are converted to underscores.

3.2.1 Optional parameter settings
import math
import argparse  # 1、导入argpase包


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')  # 2、创建参数对象
    parse.add_argument('--radius', default=2, type=int, help='Radius of Cylinder')  # 3、往参数对象添加参数
    parse.add_argument('--height', default=4, type=int, help='height of Cylinder')
    args = parse.parse_args()  # 4、解析参数对象获得解析对象
    return args


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


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))  # 5、使用解析对象.参数获取使用命令行参数

By adding - - before the parameter name , it is set as an optional parameter. If not entered, the default value will be used (if default is not set, the default value will be None), as shown in the following example:
insert image description here

3.2.2 Optional parameter reference names
import math
import argparse  # 1、导入argpase包


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')  # 2、创建参数对象
    parse.add_argument('-r', '--radius', default=2, type=int, help='Radius of Cylinder')  # 3、往参数对象添加参数
    parse.add_argument('-H', '--height', default=4, type=int, help='height of Cylinder')
    args = parse.parse_args()  # 4、解析参数对象获得解析对象
    return args


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


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))  # 5、使用解析对象.参数获取使用命令行参数

By setting optional parameters to reference names, the parameter names can be shortened and command-line parameter input is simplified:
insert image description here

As follows: Both -r and - -radius are available
insert image description here
insert image description here

3.2.3 Clear the parameter name information in the help
import math
import argparse  # 1、导入argpase包


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')  # 2、创建参数对象
    parse.add_argument('-r', '--radius', default=2, type=int, metavar='', help='Radius of Cylinder')  # 3、往参数对象添加参数
    parse.add_argument('-H', '--height', default=4, type=int, metavar='', help='height of Cylinder')
    args = parse.parse_args()  # 4、解析参数对象获得解析对象
    return args


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


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))  # 5、使用解析对象.参数获取使用命令行参数

As follows, compared with the information displayed by -h in 3.2.2, the reason for removing the parameter name is
insert image description here:
Metavar displays the parameter name in the usage description through -h.
For mandatory parameters, the default is the parameter name, and for optional parameters, the default is all uppercase parameters. name.. It will not be displayed here by setting it to empty.

3.2.4 Mandatory parameter settings
import math
import argparse  # 1、导入argpase包


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')  # 2、创建参数对象
    parse.add_argument('-r', '--radius', default=2, type=int, metavar='', required=True, help='Radius of Cylinder')  # 3、往参数对象添加参数
    parse.add_argument('-H', '--height', default=4, type=int, metavar='', required=True, help='height of Cylinder')
    args = parse.parse_args()  # 4、解析参数对象获得解析对象
    return args


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


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))  # 5、使用解析对象.参数获取使用命令行参数

When required=True is set , no matter whether the parameter is optional or not, it must be entered, as shown in the following example:
insert image description here

3.2.5 List parameter (multi-parameter) input setting
import math
import argparse


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')
    parse.add_argument('-n', '--num', type=int, nargs='+', metavar='', required=True, help='a string of nums')
    args = parse.parse_args()
    return args


if __name__ == '__main__':
    args = parse_args()
    print(args.num)
    for i in list(args.num):
        print(i)


argparse

3.2.6 Use of mutually exclusive parameters
import math
import argparse


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')
    parse.add_argument('-r', '--radius', default=2, type=int, metavar='', required=True, help='Radius of Cylinder')
    parse.add_argument('-H', '--height', default=4, type=int, metavar='', required=True, help='height of Cylinder')
    group = parse.add_mutually_exclusive_group()  # 1、在参数对象中添加互斥组
    group.add_argument('-b', '--brief', action='store_true', help='print brief message')  # 2、在互斥组中添加参数(store_true默认当命令行未输入参数则为False,否则为True)
    group.add_argument('-v', '--verbose', action='store_true', help='print verbose message')
    args = parse.parse_args()
    return args


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


if __name__ == '__main__':
    args = parse_args()
    volume = cal_vol(args.radius, args.height)
    if args.brief:
        print(volume)
    elif args.verbose:
        print('Volume of Cylinder with radius %s and height %s is %s' % (args.radius,args.height,volume))
    else:
        print('Volume of Cylinder is %s' % (volume))

In the command line, b and v can only input one of the two parameters.
insert image description here

3.2.7 Default parameter settings

set_defaults() can set the default value of some parameters

import math
import argparse


def parse_args():
    parse = argparse.ArgumentParser(description='Calculate cylinder volume')
    parse.add_argument('-r', '--radius', default=2, type=int, metavar='', required=True, help='Radius of Cylinder')
    parse.set_defaults(height=4)
    args = parse.parse_args()
    return args


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


if __name__ == '__main__':
    args = parse_args()
    print(cal_vol(args.radius, args.height))

insert image description here

4. References

Guess you like

Origin blog.csdn.net/craftsman2020/article/details/129237425