python: argparse is used for command line parameter parsing

Posted by fighter1430 on Wed, 15 Dec 2021 23:50:16 +0100

argparse is a built-in command line parsing module in python. It is built in python and can be used after importing.

Default built-in help

import argparse

parser = argparse.ArgumentParser()
print(parser.parse_args())

Save as parser tools Py, run from the command line:

>python parser-tools.py -h
usage: parser-tools.py [-h]

optional arguments:
  -h, --help  show this help message and exit

argparse.ArgumentParser is to create a parameter resolution instance. Parameter description specifies the description information of the program in the help, prog specifies the program name in the help, and epilog can specify the help information at the bottom of the help.

add_argument add parameter

Parameters can be divided into position parameters and option parameters:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-a", "--arg1", "--arg2")
parser.add_argument("-b", type = int, default = 10)
parser.add_argument("c")

print(parser.parse_args())

In the above example, a and b are option parameters and c is position parameters. The difference is whether it starts with "-". In addition, multiple identifiers can be specified for a parameter, so the a parameter can be specified with arg1 or arg2. The help information is as follows:

>python parser-tools.py -h
usage: parser-tools.py [-h] [-a ARG1] [-b B] c

positional arguments:
  c

optional arguments:
  -h, --help            show this help message and exit
  -a ARG1, --arg1 ARG1, --arg2 ARG1
  -b B

Type specifies the type of the parameter. You can know that the option parameter b is of integer type (character type by default). In addition, you can use the default value. When you do not specify a parameter, the parameter will use this default value.

>python parser-tools.py --arg2 a-string -b 1 c-string
Namespace(arg1='a-string', b=1, c='c-string')

It can be found that the a parameter is resolved as "a-string", the b parameter is resolved as 1, and C is the location parameter. At this time, it is specified as "c-string".

When a and b are not specified, the default value is used. If default is not specified, the default value of default is used None:

>python parser-tools.py  1
Namespace(arg1=None, b=10, c='1')

When a and b are not specified, a uses the default value of 10 because no default value is specified.

nargs can specify how many data a parameter accepts:

N: An integer representing the specified number;

*: accept any parameter, including zero, and the result is a list;

?: Zero or one;

+: at least one, otherwise an error is reported;

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-d", nargs="?", const="d const value", default="d default value")
parser.add_argument("-e", action="store_const", const="e const value", default="e default value")
parser.add_argument("-f", nargs="*")

print(parser.parse_args())

because? It means to accept 0 or 1 parameters. When a parameter is specified but no parameter value is passed, if const value is set at this time, const value will be used at this time.

>python parser-tools.py -d -f
Namespace(d='d const value', e='e default value', f=[])

It can be found that when the d parameter is specified but no specific parameter value is passed in, the const value will be used. Since the e parameter is not specified, the default value is used. Any value defined when the f parameter is not passed to it, so it is an empty list.

const is "? In nargs Or action is "store"_ const "is useful when equivalent, for example:

>python parser-tools.py -d -e -f 1 3 str
Namespace(d='d const value', e='e const value', f=['1', '3', 'str'])

It can be found that the action of the e parameter is store_const. As a result, after specifying the e parameter, its value is the const value used.

action is how to process the parameter value after receiving the command line parameter. By default, it is the stored value. For example, f in the above example passes in three parameters 1,3 STR, and the parsing result is a list containing the three.

action can be specified as follows:

store_const: when a parameter is specified, the value of the parameter will be resolved to the value of const;

store_true and store_false: and store_const is similar, except that the value of const is automatically true or false;

append: stored as a list. It can be used when a parameter needs to be used multiple times;

append_const: store as a list and append the value of const to the list;

count: counts the number of occurrences of a parameter;

Help: by default, the h parameter of a print help has been automatically added;

Version: print version number. You need to specify the value of version at the same time;

extend: store as a list and add each parameter to the list.

import argparse

parser = argparse.ArgumentParser()

__VERSION__ = "0.0.1"

parser.add_argument("-v", "--version", action="version", version=__VERSION__)
parser.add_argument("-g", action="append_const", const="const-val")
parser.add_argument("-i", action="count")

print(parser.parse_args())

Print the version number as follows:

>python parser-tools.py -v
0.0.1

If a parameter is used multiple times, the analysis result is as follows:

>python parser-tools.py -gg -iii
Namespace(g=['const-val', 'const-val'], i=3)

In addition, the choices parameter specifies the optional value of the parameter, required represents the required parameter, and dest represents the variable name after the parameter is parsed.

add_subparsers can add subcommands

import argparse

parser = argparse.ArgumentParser(
    description="Test sub commond", 
    prog="Parse-Tools",
    epilog="More help message here..."
)

sub_parser = parser.add_subparsers()

sub_a = sub_parser.add_parser("A")
sub_b = sub_parser.add_parser("B")

sub_a.add_argument("-aa", "--A_Arg")
sub_b.add_argument("-bb", "--B_Arg")

print(parser.parse_args())

add_ Add subcommands A and B to the parser object returned by subparsers. Each subcommand can continue to add argument. The results are as follows:

# Help information
>python parser-tools.py -h
usage: Parse-Tools [-h] {A,B} ...

Test sub commond

positional arguments:
  {A,B}

optional arguments:
  -h, --help  show this help message and exit

More help message here...

# Subcommand A help information
>python parser-tools.py A -h
usage: Parse-Tools A [-h] [-aa A_ARG]

optional arguments:
  -h, --help            show this help message and exit
  -aa A_ARG, --A_Arg A_ARG

# Subcommand A
>python parser-tools.py A -aa test
Namespace(A_Arg='test')