Python3 command line module argparse concise tutorial

Python3's own module argparse is specially used to process command line parameters. Users can write the command line parameters they need, which is very powerful.

This article mainly describes its basic usage. The Python version is 3.8.3. You can also directly refer to the official documentation of argparse .


One use step

First, explain the steps of use, and then we will talk about examples, which are mainly divided into three steps.

1. Create Parser

Use the class argparse.ArgumentParser, which is defined as follows,

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)

There are many parameters, but there are only a few commonly used (in bold), and the remaining parameters use the default values.

2. Add command line parameters

This step is the most critical, use the add_argument() method of ArgumentParser

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

This method defines how to parse a single command line parameter

3. Parse the parameters

Use the parse_args() method of ArgumentParser,

ArgumentParser.parse_args(args=None, namespace=None)

Generally speaking, the default values ​​of these 2 parameters are sufficient, and we only need to receive the return value of the function when parsing.


Two examples

With the previous general understanding, let's take a look at how to use it. Through examples, we can have a deeper understanding of the use of argparse.

1 Command line parameters are multiple data

That is, the command line parameters are direct data or other strings. Such parameters are called positional arguments.

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('integers', metavar='N',
					type=int, nargs='+',
					help='an integer for the accumulator')

args = parser.parse_args()

print(args.integers)

View the help information,
Insert picture description here
the parameter analysis of add_argument() in this example:

  • The first parameter defines the command line parameter name, namely integers
  • The second parameter metavar is the parameter name displayed in the definition help message. If it is missing, the command line parameter name will be used directly, that is, integers
  • The third parameter type is used to define the command-line parameter type. The int given here means that only the command-line parameter of integer data is accepted, and it will be automatically converted to integer during parsing. If it is missing, it will be stored as a string.
  • The fourth parameter nargs defines the allowable number of occurrences of the command line parameter. Here, "+" is used, which means at least once; if it is "*", it means 0, 1 or more times; if it is "?", then Indicates that it appears at most once; it can also be a specific number, such as 1, 2, 3, etc. In fact, the symbols in regular expressions are used here
  • The fifth parameter help is used to add help information for command line parameters

Operation mode:python aa.py 100 200 300

2 The form of the parameter followed by the value

Generally speaking, unix-style command lines are used more frequently, that is, the form of "prog -arg xx", that is, a parameter followed by a parameter value, this kind of parameter is called optional arguments

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-a', dest='A_value', type=int, metavar='value',
                    help='Store a simple value', default=100)

args = parser.parse_args()

print(args.AA_value)

View help information,
Insert picture description here

It can be seen that -a is wrapped in square brackets, which means it is optional. If the parameter is not passed, the default value is used, and if the parameter is passed, the passed value is used.
The parameter analysis of add_argument(),

  • The first parameter is to define the command line parameter name
  • The second parameter dest defines the variable name corresponding to the command line parameter during parsing. If it is missing, use the command line parameter name directly
  • The 3rd, 4th and 5th parameters will not be repeated
  • The sixth parameter default defines the default value

The main purpose is to understand the meaning of dest. After the parameter is parsed, an object will be obtained. This object contains the value corresponding to the parameter (whether it is the default value or the value passed by the command line). How to get this value? Use args.AA_value to get it, if dest is missing, get it via args.a.

How to use: python aa.py -a 300orpython aa.py

PS: dest can only be used for optional arguments, not for positional arguments, because positional arguments already use the command line parameter name as dest.

As mentioned earlier, this added -a parameter is optional when used. If the -a parameter is required to appear on the command line, then the required parameter must be used, as follows,

parser.add_argument('-a', type=int, metavar='value', dest='A_value',
                    help='Store a simple value', required=True)

The required value added at the end is set to True, which means that you must pass parameters from the command line. Check the help information.
Insert picture description here
You can see that the square brackets around -a are gone. Because the parameters must be passed, the default value is not needed.

3 Pass true/false value

Sometimes I want to use command line parameters to pass true/false values. For example, prog -b means that a true is passed, without -b means that a false is passed, that is, the default value of -b is false.

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-b', action='store_true', dest='B_value',
                    help='Turn on a light')

args = parser.parse_args()

print(args.B_value)

Help information,
Insert picture description here
usage
Insert picture description here
, the action parameter in add_argument() is the key, here is "store_true", which means that if -b appears, it will be converted to True, if not, it will be converted to False. Similarly, there are other values ​​available select,

  • store_false: turn to False if the parameter appears, turn to True if it does not appear
  • store_const: When the parameter appears, it is converted to a fixed value, which is specified by const
  • append: multiple parameters with the same name are allowed, and the value is stored in the list
    ...

There are many other options, you can directly refer to the official document

4 Pass a fixed value

Understand Case3, this is easy to understand, just set the value of action to "store_const" and use const to specify the value

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-c', action='store_const', const=100, dest='C_value',
                    help='Give a value')

args = parser.parse_args()

print(args.C_value)

Use as follows,
Insert picture description here
if you do not use -c will pass None

5 multiple parameters with the same name

Sometimes you need to pass multiple parameters of the same type, so there will be multiple parameters with the same name,

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-d', action='append', type=int, metavar='value', dest='D_value',
                    help='Get a value')

args = parser.parse_args()

print(args.D_value)

How to use it,
Insert picture description here

6 One parameter followed by multiple values

Just use nargs,

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-e',  nargs='+', type=int, metavar='value', dest='E_value',
                    help='Get one or more value')

args = parser.parse_args()

print(args.E_value)

Use as follows,
Insert picture description here

7 Specify the value range of the parameter

You need to use choice in add_argument(),

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('-g', type=int, metavar='value', 
                      choices=range(1, 4), dest='G_value')

args = parser.parse_args()

print(args.G_value)

In this way, only one of the three values ​​1,2,3 can appear after -g,
Insert picture description here


Three understanding of positional and optional

From the front, we can see that the parameters are divided into two types, positional and optional. How to understand? You can look at the following function,

def func(data1, data2, data3=100, data4=200):
	print("data1: {}".format(data1))
	print("data2: {}".format(data2))
	print("data3: {}".format(data3))
	print("data4: {}".format(data4))

func(10, 20)
print("\n")
func(20, 40, data4=50, data3=20)

The parameters data1 and data2 must be passed by value, and the position is immutable. Data3 and data4 can be passed by value or not. The cut position can be changed, but it must be after data1 and data2.

data1 and data2 are positional parameters, data3 and data4 are optional parameters. Of course, there is still a slight difference corresponding to the command line

'''
filename: aa.py
'''

import argparse

parser = argparse.ArgumentParser(description='Process cmdline args.')

parser.add_argument('integers', metavar='N',
					type=int, nargs='+',
					help='an integer for the accumulator')

parser.add_argument('-f',  type=int, metavar='value', dest='F_value',
                    help='Get a value')

args = parser.parse_args()
print(args.integers)
print(args.F_value)

The help information is as follows, and the
Insert picture description here
usage is as follows.
Insert picture description here
If the nargs of the -f parameter is set to "+", then the third case in the above figure will also be correct.


Four summary

This article mainly describes the general usage of argparse. Of course, there are various usage methods that are not mentioned in this article. If you are interested, you can refer to the official documentation.

Guess you like

Origin blog.csdn.net/whahu1989/article/details/108358399