目录
一. 实例
# -*- coding: UTF-8 -*-
import argparse
def main():
parser = argparse.ArgumentParser(description="This is a example program")
# 字符串类型
parser.add_argument('-f', '--file', action='store', help='just a test', dest='fore_name')
# 不带参数
parser.add_argument('-v', '--verbose', action='store_false', default = True)
# 带多个参数
parser.add_argument('-m', '--mag', nargs='+')
# 创建两个互斥的参数,如果同时出现,则会报异常。
group = parser.add_mutually_exclusive_group()
group.add_argument("-a", "--aa", action="store_true")
group.add_argument("-b", "--bb", action="store_true")
# 限定某个参数范围
parser.add_argument('-c', '--cc', type=int, choices=range(5, 10))
parser.add_argument('-d', '--dd', choices='abc')
# 设置为必选参数
parser.add_argument('-e', '--ee', required=True, help = 'the must input arg')
# 解析参数
ut_flag = True
if ut_flag is not True:
args = parser.parse_args()
else:
test_str = '-f file.txt -v -m a b c -a -d a -e b'
test_args = test_str.split()
# 解析测试参数
args = parser.parse_args(test_args)
# 访问其中的一个参数
print(args.ee)
print(args)
if __name__ == "__main__":
main()
二. 参数解析
- name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo。
- action - 命令行遇到参数时的动作
- store:这个只是简单的存储这个参数值,这也是默认操作。
- store_const: 存储const指定的值。
- store_false和store_true:分别对应存储True和False值。它们是store_const的特例。
- append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值;
- append_const:保存为列表,但是值必须是const指定参数的值。
- count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析;
- nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用 default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数。
- const - action 和 nargs 所需要的常量值。
- default - 不指定参数时的默认值。
- type - 命令行参数应该被转换成的类型。str, int,file
- choices - 有时候需要限制参数在某个范围之内,这时可以通过choices提供这个参数范围,如果提供的参数值不在这个范围之内,那么会报错。
- required - 一般情况下,argparse模块将带"-"前缀(例如-f)或者带"--"前缀的(例如--bar)的参数视为可选参数,,为了使可选参数变成必须参数,可以设置required值为True。
- help - 参数的帮助信息,当指定为
argparse.SUPPRESS
时,表示不显示该参数的帮助信息. - metavar - 当ArgumentParser生成帮助信息的时候,它需要通过某种方式来引用参数,对于位置参数,参数直接引用,对于可选参数,将其转换成大写再引用。
- dest -对于可选参数,dest的值根据可选参数的不同而相应改变,如果是完整字符串,使用去掉--前缀之后的字符串,如果是简短名,则使用去除-前缀之后的字符串,如果字符串中间带有-,则将-替换成_以使这个字符串合法。
参考博客:
https://www.cnblogs.com/fireflow/p/4826985.html
https://www.cnblogs.com/fireflow/p/4827005.html
https://www.cnblogs.com/fireflow/p/4841389.html
来源:CSDN
作者:vertor11
链接:https://blog.csdn.net/vertor11/article/details/103745174