argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数。
一、argparse传递参数
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
参数解释:
name or flags
Either a name or a list of option strings, e.g. foo or -f, --foo. 用于标识参数的参数,必须有,通常以-或–来表示
from argparse import ArgumentParser
parse = ArgumentParser.add_argument('--s','-s')
action
action - The basic type of action to be taken when this argument is encountered at the command line. 默认是store,表示存参数的值,store_const 表示以常量的形式来存储,append 列表,append_const 列表常量。
nargs
nargs - The number of command-line arguments that should be consumed
nargs=2 表示包含两个值的参数列表
nargs=’*’ 表示任意个参数
nargs=’+’ 表示至少一个参数
default
默认值
type
参数的数值类型
choices
给定候选的值
required
是否为必须给定的参数
help
参数解释
dest
这个参数相当于把位置或者选项关联到一个特定的名字
metavar
这个参数用于help信息输出中
备注:在python脚本中经常看到 action = "store_true,如下:
parser.add_argument(
'--image', default=False, action="store_true",
help='Image detection mode, will ignore all positional arguments'
)
如果运行代码时加了 --image ,那么 image为true
如果没加 --image,那么image为False
二、获取和终端替换参数名
增加了两个参数name和year,其中’-n’,’–name’表示同一个参数,default参数表示我们在运行命令时若没有提供参数,程序会将此值当做参数值。
详细解释请看源码:
import argparse
#导入模块
def main():
parser = argparse.ArgumentParser(description="Demo of argparse")
parser.add_argument('-n','--name', default=' zhouxiao ')
parser.add_argument('-a','--age', default='23') #增加的参数信息
parser.add_argument('-y','--year', default='2021') #增加的参数信息
args = parser.parse_args() #获取解析的参数
print(args) #打印解析的参数
name = args.name
age = args.age
year = args.year
print('Hello {} {} {}'.format(name,age,year))
if __name__ == '__main__':
main()
执行结果:
Namespace(age='23', name=' zhouxiao ', year='2021')
Hello zhouxiao 23 2021
终端打印并替换参数:cmd在上述文件目录下打开集成终端,输入下面的命令:
python argparse_test.py -n zhang --age '19' --year '2022'
执行结果:
Namespace(age='19', name='zhang', year='2022')
Hello zhang 19 2022
当执行命令argparse_test.py -h可以查看帮助信息,执行结果:
Demo of argparse
optional arguments:
-h, --help show this help message and exit
-n NAME, --name NAME
-a AGE, --age AGE
-y YEAR, --year YEAR
三、传入列表作为参数
先新建一个文件:agr.py
#默认情况下,它带有多个参数。
parser.add_argument('-默认')
#告诉类型为列表也会因多个参数而失败,
#但仅对于单个参数给出错误的结果。
parser.add_argument('-list-type',type = list)
#这将允许您提供多个参数,但是您将获得
#不需要的列表清单。
parser.add_argument('-list-type-nargs',type = list,nargs ='+')
#这是处理接受多个参数的正确方法。
#'+'== 1或更大。
#'*'== 0或更大。
#'?' == 0或1。
#int是要接受的显式参数。
parser.add_argument('-nargs',nargs ='+')
#输入整数
parser.add_argument('-nargs-int-type',nargs ='+',type = int)
#一种接受多种输入的替代方法,但是您必须
#每个输入提供一次标志。
parser.add_argument('-append-action',action ='append')
#命令终端显示给定选项屏幕的结果
源码:
import argparse
parser = argparse.ArgumentParser()
# By default it will fail with multiple arguments.
parser.add_argument('--default')
# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)
# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')
# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')
# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)
# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')
# To show the results of the given option to screen.
list_arg = []
for _, value in parser.parse_args()._get_kwargs():
if value is not None:
list_arg.append(value)
print(value)
print((',').join(str(x) for x in list_arg))
list_arg = (' ').join(str(x) for x in list_arg)
# print(len(list_arg))
cmd 终端输入并生成列表结果:
中间的空格同样被保存在一个列表中:
(gpu) PS D:python agr.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']
保存在多维列表中,按数字一个个生成列表
python agr.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]
按空格分割分成几个列表:
python agr.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']
['1234', '2345', '3456', '4567']
将字符数字转化为整形数据类型:
python agr.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]
[1234, 2345, 3456, 4567]
适当加一些运算符号:
python agr.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]
提供字符标志:
python agr.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']