Python argparse module
What is argparse module
argparse is the standard python module for parsing command-line arguments and options, replacing the deprecated optparse module. argparse is used to parse command-line arguments.
Many times we need to use programs that parse command line arguments.
argparse module Steps to use
We can often simplify the use of argparse to the following four steps:
1:import argparse
2:parser = argparse.ArgumentParser()
3:parser.add_argument()
4:parser.parse_args()
The above four steps are explained as follows:
- first import the module; then create a parsing object;
- then add the command line arguments and options you want to focus on to the object, each add_argument method corresponds to an argument or option you want to focus on;
- finally call the parse_args() method for parsing; after successful parsing, you can use it.
argparse module Demo
Let’s use an example to illustrate.
We can see the second step above: parser = argparse.ArgumentParser()
.
What it does is: when parser.print_help()
is called or when running the program due to incorrect arguments (at this point the python interpreter actually calls the spring_help() method as well), it prints this description information, usually just passing the description argument.
Example output will be given below, starting with the code.
#-*- coding: UTF-8 -*-
import argparse #Step 1
def parse_args():
"""
:return:Parsing of parameters
"""
description = "you should add those parameter" # Step 2
parser = argparse.ArgumentParser(description=description) # These parameters have default values when calling parser.print_help() or when running the program due to incorrect parameters (when the python interpreter actually calls the spring_help() method as well)
# will print this description information, and generally only the description parameter needs to be passed, as above.
help = "The path of address"
parser.add_argument('--addresses',help = help) # Step 3, followed by the help is my description
args = parser.parse_args() # Step 4
return args
if __name__ == '__main__':
args = parse_args()
print(args.addresses) #Just get it directly that way.
Each of the four steps above has been corresponded to when we type in at the command line.
python arg.py -h
The output prompt is.
argparse module How to get command parameter values
We can get its parameter values directly from args.addresses
.
When we type the command python arg.py --addresses this-is-parameter-of-addresses
we will output this-is-parameter-of-addresses
.
This summarizes some of the common uses of the argparse module.