Python command line parameter parsing learning

The argparse module has a lot of parameters. I am not familiar with this, and I don’t know the command line very well.

 

 

Standard module for parsing command line options and arguments.

Steps for usage:

1: import argparse #import module

2: parser = argparse.ArgumentParser() #Create a parsing object

3: parser.add_argument() #Add the command line options and parameters used to the object

4: parser.parser_args() #parse the command line

==================================================================

Create an instance of ArgumentParser, ArgumentParser parameters are keyword parameters.

prog : file name, the default is sys.argv[0], used to describe the name of the program in the help information.

usage : a string describing the usage of the program

description : the information displayed before the help information

epilog : information displayed after the help message

 

=====================================================================================================

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

The commonly used parameters are explained as follows:

name or flags: command line parameter names or options, such as -p, --port

action:

    store: The default action mode, stores the value to the specified variable

    store_const: The stored value is specified in the const part of the parameter, which is often used to implement non-boolean command line flags

    store_true/store_false: Boolean switch. The default value of store_true is False, if the Boolean switch is entered on the command line, the value is True. store_false instead

    append: store the value to a list, this parameter can be reused

    append_const: store the value to the list, the stored value is specified in the const part of the parameter

    count: the number of inputs for the shorthand of the statistical parameter

    version: output version information, then exit the script

nargs: The number of command-line arguments, generally represented by wildcards: ? Indicates that only one is used, * means 0 to multiple, + means 1 to multiple

default: default value

type: the type of the parameter, the default is string type, and can also be float, int, boolean and other types

choices: range of input values

required: The default is False, if it is True, it means that the parameter must be entered

help: help message to use

dest: The corresponding variable name of the parameter in the program, such as: add_argument("-a", dest="code_name"), use parser.code_name in the script to access the value of the command line option

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522920&siteId=291194637