Quick Start Python built-in module argparse

1. Introduction to argparse

argparseThe module is a built-in module in Python for command item options and parameter parsing. argparseThe module can make it easy to write a user-friendly command line interface, and can help programmers define parameters for the model.

Four steps to use the argparse module:

①Import the argparse package

import argparse

②Create a command line parser object

# 创建 ArgumentParser() 对象
parser_ = argparse.ArgumentParser(description="study argparse")

Add command line parameters to the parser - call the add_argument() method to add parameters

parser_.add_argument('food')

Parse the parameters of the command line - use parse_args() to parse the added parameters, and output the results with the print statement

args = parser_.parse_args()
print(args.food)
print(type(args.food))

Code example:

# -*- coding: utf-8 -*-
# @Time    : 2023-04-19 15:48
# @Author  : AmoXiang
# @File    : test.py
# @Software: PyCharm
# @Blog    : https://blog.csdn.net/xw1680

import argparse  # 1.导入argparse

# 2.创建一个命令行解析器对象
parser_ = argparse.ArgumentParser(description="study argparse")
# 3.给解析器添加命令行参数
parser_.add_argument('food')
# 4.解析命令行的参数并打印
args = parser_.parse_args()
print(args.food)
print(type(args.food))

The result of the operation is as follows:
insert image description here
Interpret the above code:

First we import argparsethis package, and then the ArgumentParser class in the package generates a parser object (the description describes the function of the parameter parser), and when we display the help information on the command line, we will see the information described by the description. For example: python test.py -h
insert image description here
Then we add parameters through the object's add_argument function. Here we add the food parameter, and finally use the parse_args of the object to get the parsed parameters. The print result is shown in the figure below:
insert image description here

二、The add_argument() method

The add_argument() method defines how to parse a single command line argument, the syntax is as follows:

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

Parameter explanations that will be used in subsequent sample codes:

① name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. 必要参数
② choices - A container of the allowable values for the argument.
③ type - The type to which the command-line argument should be converted.
④ default - The value produced if the argument is absent from the command line.
⑤ help - A brief description of what the argument does.

The first way of writing name or flags is as follows:

import argparse

parser_ = argparse.ArgumentParser(description="study argparse")
# 该种方式则要求必须输入该参数
parser_.add_argument('food')
args = parser_.parse_args()
print(args.food)
print(type(args.food))

Command line operation mode:

E:\download\AccountPool-master>python3 test.py 2
2
<class 'str'> 这种方式会将 2 赋值给food

E:\download\AccountPool-master>python3 test.py noodles
noodles
<class 'str'> 这种方式会将 noodles 赋值给food

The second way of writing name or flags is as follows:

# 1.--house 代表参数名称
# 2.type 代表输入的参数类型,从命令行输入的参数,默认是字符串类型
# 3.default 代表如果该参数不输入,则会默认使用该值
import argparse

parser_ = argparse.ArgumentParser(description="study argparse")
parser_.add_argument('--house', type=int, default=0)
args = parser_.parse_args()
print(args.house)
print(type(args.house))

Command line operation mode:

E:\download\AccountPool-master>python3 test.py --house 1
1
<class 'int'>

E:\download\AccountPool-master>python3 test.py
0
<class 'int'>

The third way of writing name or flags is as follows:

# -gf 代表短选项,在命令行输入-gf和--girlfriend的效果是一样的,作用是简化参数输入
# --girlfriend 代表完整的参数名称,可以尽量做到让人见名知意,需要注意的是如果想通过解析后的参数取出该值,必须使用带--的名称
# choices 代表输入参数的只能是这个choices里面的内容,其他内容则会保错
import argparse

parser_ = argparse.ArgumentParser(description="study argparse")
parser_.add_argument('-gf', '--girlfriend', choices=['jingjing', 'lihuan'])
parser_.add_argument('food')
args = parser_.parse_args()
print(args.food)
print(type(args.food))
print(args.girlfriend)
print(type(args.girlfriend))

Command line operation mode:

E:\download\AccountPool-master>python3 test.py --girlfriend jingjing
usage: test.py [-h] [-gf {
    
    jingjing,lihuan}] food
test.py: error: the following arguments are required: food

E:\download\AccountPool-master>python3 test.py --girlfriend jingjing amoxiang
amoxiang
<class 'str'>
jingjing
<class 'str'>

E:\download\AccountPool-master>python3 test.py -gf jingjing amoxiang
amoxiang
<class 'str'>
jingjing
<class 'str'>

E:\download\AccountPool-master>python3 test.py -gf amoxiang1 amoxiang2
usage: test.py [-h] [-gf {
    
    jingjing,lihuan}] food
test.py: error: argument -gf/--girlfriend: invalid choice: 'amoxiang1' (choose from 'jingjing', 'lihuan')

Guess you like

Origin blog.csdn.net/xw1680/article/details/130246259