Introduction to argparse

1. Introduction to argparse

The argparse module is Python's built-in module for command item options and parameter parsing. The argparse module makes it easy to write user-friendly command-line interfaces and helps programmers define parameters for models.

  1. argparse defines four steps
  • Import the argparse package -- import argparse
  • Create a command line parser object - create an ArgumentParser() object
  • Add command-line arguments to the parser - call the add_argument() method to add arguments
  • Parsing command line arguments - use parse_args() to parse added arguments

2. Take a chestnut

# 导入库
import argparse
 
# 1. 定义命令行解析器对象
parser = argparse.ArgumentParser(description='Demo of argparse')
 
# 2. 添加命令行参数
parser.add_argument('--epochs', type=int, default=30)
parser.add_argument('--batch', type=int, default=4)
 
# 3. 从命令行中结构化解析参数
args = parser.parse_args()
print(args)
epochs = args.epochs
batch = args.batch
print('show {}  {}'.format(epochs, batch))

To interpret the above code in vernacular, first we import the argparse package, and then the ArgumentParser class in the package generates a parser object (the description describes the function of the parameter parser), when we display the help information on the command line You will see the information described in description. For example: python try.py -h

Then we add parameters through the object's add_argument function. Here we add the epochs and batch parameters commonly used in training, and finally use the parse_args of the object to obtain the parsed parameters. The print result is shown in the figure below:

Or execute the command python fun_test.py --epochs 30 --batch 4

2. Detailed explanation of parameters

1. add_argument() method

(1) Add command line parameters

Adding program parameter information to an ArgumentParser is done by calling the add_argument() method. Typically, these calls specify how the ArgumentParser takes command-line strings and converts them into objects. This information is stored in the ArgumentParser instantiated object when parse_args() is called for subsequent use. The add_argument() method defines how to parse the command line parameters?

(2) The add_argument() method defines how to parse command line parameters

parser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][,choices][, required][, help][, metavar][, dest])

Each parameter is explained as follows:

  • name or flags: the name or label of the common parameter or flag parameter option parameter, such as epochs or -e, --epochs. The Flag parameter does not need to specify a parameter value, but only needs to have a parameter name.
  • action: The action when the command line encounters the flags parameter. There are two common actions, store_true: set the flag parameter to true; store_false: set the flag parameter to False. Note: If you run the program directly, the variable is not read by default, and you must pass parameters to use it, for example: python try.py --epochs
  • nargs: The number of command line parameters that should be read, which can be a specific number, or a ? number. When no value is specified, use default for Positional argument, and const for Optional argument; or * number, indicating 0 or more parameter; or a + sign for 1 or more parameters.
  • default: The default value of the parameter when no parameter is specified.
  • type: The data type to which the command-line argument should be converted.
  • required: Whether it is a required parameter or an optional parameter.
  • help: Help information for the parameter.
  • metavar: The parameter name in the usage description. For mandatory parameters, the default is the parameter name, and for optional parameters, the default is the parameter name in all uppercase.
  • dest: The parsed parameter name, by default, the longest name is chosen for optional parameters, dashes are converted to underscores.
  • choices: A container of allowed values ​​for the parameter.
  • const: The constant value required by action and nargs.
  • store_const: indicates 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: save a value defined in the parameter specification to a list;
  • count: store the number of encounters; in addition, you can also inherit argparse.Action to customize parameter parsing;

2. Parse the parameters of the command line: parse_args()

The ArgumentParser object parses the arguments of the command line through the parse_args() method. It will check each parameter in the command line, convert it to the appropriate data type, and then call the corresponding operation, and store the parameter structure in the object args.

args = parser.parse_args()

In scripts, normally parse_args() will be called with no arguments, and ArgumentParser will automatically determine the command-line arguments from sys.argv.

Guess you like

Origin blog.csdn.net/feichangyanse/article/details/128559542