argparse、ConfigParser 简易使用教程
argparse: 命令行解析
ConfigParser: 配置文件解析
1. argparse
argparse是Python中用于解析命令行参数的一个模块,可以自动生成help和usage信息;当从终端输入的参数无效时,模块会输出提示信息。
1.1 实例化ArgumentParser
# argparse使用流程
import argparse
# step1.创建ArgumentParser对象parser,
## ->parser 保存了所有必要信息,用于将从命令行中读入的参数 解析为对应的python数据类型。
## ->description,用于简要介绍程序的功能和工作原理。在帮助消息中,显示在命令行用法字符串 和 各种参数的帮助消息之间。
## ->prog,用于显示“程序文件名”,默认为“运行文件名”
## ->usage,程序使用说明。当使用了 usage 的参数之后,会覆盖覆盖了 prog 参数里面的值。
parser = argparse.ArgumentParser(description="process some integer.")
# step2: 给parser添加信息读取字段,这些字段决定parser解析读入参数的方法
## ->parser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
## ->name,用于保存输入变量
## ->action='store_const' 存储由const关键字参数指定的值。
## ->default变量的默认输入,如果未解析到相关参数,解析器会将该值解析为一个命令行参数,
## ->type 指定变量的类型
## ->nargs单个命令行参数与要执行的单个操作相关联
## nargs='+'.'+'和'*'一样,出现的所有命令行参数都被收集到一个列表中。
## 当ArgumentParser生成帮助信息时,默认情况下使用dest的值作为每个对象的“名字”,metavar会改变显示出来的名字 - parse_args() 对象中属性的名字仍然由dest的值决定。(metavar: 这个参数用于help 信息输出中)
parser.add_argument()
# step3:解析parser保存的参数,返回一个命名空间,在实际python脚本中parse_args()一般不使用参数,它的参数由sys.argv确定。
args = parser.parse_args()
1.2 必选参数/可选参数
todo
1.3 action
argparse内置6种动作可以在解析到一个参数时进行触发:
- store 保存参数值,可能会先将参数值转换成另一个数据类型。若没有显式指定动作,则默认为该动作。
- store_const 保存一个被定义为参数规格一部分的值,而不是一个来自参数解析而来的值。这通常用于实现非布尔值的命令行标记。
- store_ture/store_false 保存相应的布尔值。这两个动作被用于实现布尔开关。
- append 将值保存到一个列表中。若参数重复出现,则保存多个值。
- append_const 将一个定义在参数规格中的值保存到一个列表中。
- version 打印关于程序的版本信息,然后退出
# store_ture/store_false demo 【终端命令带上之后会使用默认值】
## action=store_ture, 若输入命令时未加--cuda, args.cuda=False,
## action=store_ture, 若输入命令时 加--cuda, args.cuda=True,
parser.add_argument('--cuda', action='store_true', help='enables cuda')
# 终端命令不加入--cuda, args.cuda=False, 终端命令加入--cuda, args.cuda=True
parser.add_argument('--cuda', action='store_false', help='enables cuda')
# 终端命令不加入--cuda, args.cuda=True, 终端命令加入--cuda, args.cuda=False
1.4 help信息显示
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="xxxx")
parser.add_argument("--nz", type=int, default=100, help="size of noise")
args = parser.parse_args()
print(args.nz)
python test.py --h # 或者python test.py --help
输出
usage: test.py [-h] [--nz NZ]
xxxx
optional arguments:
-h, --help show this help message and exit
--nz NZ size of noise
1.5 argparse使用demo-实现加法器
调用 parse_args() 将返回一个具有两个属性的对象, integers 和 accumulate 。累和语句实现,默认对输入的数据进行求最大,如果解析到sum的参数,那么求和
import argparse
parser = argparse.ArgumentParser(description="process some integer.")
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for accumulator') # 可以读一个数组
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default:find the max)'
args = parser.parse_args()
print(args.accumulate(args.integers)) # 居然可以当作函数调用
上面程序实现了,默认求最大,可选求和的功能,结合上面程序,讲解三个函数中常用的选项含义:
1.6 D-Model parser
模型常见可指定参数类型,可选值,默认值,和帮助信息等,在运行程序的时候通过命令行输入用户制定的参数,否则使用默认参数。
更多内容可以详见以下三篇博文:
https://cloud.tencent.com/developer/section/1370514
https://www.cnblogs.com/piperck/p/8446580.html
https://blog.csdn.net/LemonTree_Summer/article/details/80749359
2. ConfigParser
import ConfigParser # python2.x
import configparser # python3.x
模块定义了一个ConfigParser类, 使用类成员方法RawConfigParser()、ConfigParser()、 SafeConfigParser() 对指定的配置文件进行增、删、查、改。
2.1 配置文件格式约定
# test.conf内容如下, 方括号[]中的内容为为section
# 每个section内部以类似于key-value的形式配置参数,支持 ‘=’、‘:’ 两种形式分隔key-value对
# key在configparser被叫做option
# "#" 和";" 表示注释, 注释不能放在有效数据行后,会影响数据读取,例如:
# batch_size = 32 # enen 使用config.getint("sample", batch_zise)报错ValueError: invalid literal for int() with base 10: '32 # enen'
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Tom
[topsecret.com]
Port: 50022
ForwardX11: no
is_safe = True
is_danger = False
score = 1.2
2.2 实例化configparser
实例化 configparser: 读配置文件、读字典
(已经有字典的话,再构建configparser对向似乎多此一举,所以推荐用于读配置文件)
import configparser
# 读配置文件
config = configparser.ConfigParser()
config.read("test.conf") # 配置文件的路径
# 读字典
parser = configparser.ConfigParser()
parser.read_dict({'section1': {'key1': 'value1',
'key2': 'value2',
'key3': 'value3'},
'section2': {'keyA': 'valueA',
'keyB': 'valueB',
'keyC': 'valueC'},
'section3': {'foo': 'x',
'bar': 'y',
'baz': 'z'}
})
2.3 增、删、查、改
# Python 2.7.18 版本不同,接口函数略有区别
>>> import ConfigParser
>>> config = ConfigParser.ConfigParser()
>>> config.read("test.conf")
['test.conf']
>>> config.sections() # 获取所有sections,过滤[DEFAULT]
['bitbucket.org', 'topsecret.com']
>>> config.items("topsecret.com") # 获取指定section的keys-values,[DEFAULT]也会显示
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'no'), ('port', '50022'), ('is_safe', 'True'), ('is_danger', 'False'), ('score', '1.2')]
>>> config.options('topsecret.com') # 获取指定section的keys
['port', 'forwardx11', 'is_safe', 'is_danger', 'score', 'serveraliveinterval', 'compression', 'compressionlevel']
>>> config.get('bitbucket.org', 'User') # 获取指定key的value (不同类型数据获取方法如下)
'Tom'
>>> config.getint('topsecret.com', 'Port')
50022
>>> config.getboolean("topsecret.com", "is_safe")
True
>>> config.getboolean("topsecret.com", "is_danger")
False
>>> config.getfloat("topsecret.com", "score")
1.2
>>> config.add_section('Section_1') # 增加section、元素、写入配置文件
>>> config.sections()
['bitbucket.org', 'topsecret.com', 'Section_1']
>>> config.set('Section_1', 'key_1', 'value_1')
>>> config.write(open('test.conf', 'w'))
>
>>> config.remove_option('Section_1', 'key_1') # 删除元素、section, 写入配置文件
True
>>> config.remove_section('Section_1')
True
>>> config.write(open('test.conf', 'w'))