configparser
Configuration file parser
A setup file consists of sections, lead by a “[section]” header,and followed by “name: value” entries
0.0, 常用函数
0.1,读取
read(filename)----> 直接读取文件内容
sections() ----> 得到所有的section,并以列表的形式返回
options(section) ----> 得到该section的所有option
items(section) ----> 得到该section的所有键值对
get(section,option) ----> 得到section中option的值,返回为string类型
getint(section,option) ----> 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
0.2,写入
write(fp)----> (fp->file文件) 将config对象写入至某个 .init 格式的文件 Write an .ini-format representation of the configuration state.
add_section(section) ----> 添加一个新的section
set( section, option, value) ----> 对section中的option进行设置,需要调用write将内容写入配置文件 ConfigParser2
remove_section(section) ----> 删除某个 section
remove_option(section, option) ----> 删除某个 section 下的 option
0.3,详例
from configparser import ConfigParser
cp = ConfigParser()
#加载配置文件
cp.read('model.cfg')
config_params={}
#获取每个section,返回list
for section in cp.sections():
print(section)
#获取每个setction中的options
for option in cp.options(section):
#获取每个section中option的value
print(option,':', cp.get(section,option))
config_params[option] = cp.get(section,option)
print(config_params)
#获取同一个section下的所有键对值
print(cp.items('image_path'))
print('---------------写入 部分---------------------')
#移除选项
cp.remove_option('image_size','image_width')
cp.remove_option('image_size','image_height')
#新增sections
cp.add_section('img_s')
#新增选项,并给相应选项赋值
cp.set('img_s','img_w','400')
cp.set('img_s','img_h','400')
#移除整个sections
cp.remove_section('image_path')
cp.add_section('img_p')
cp.set('img_p','img_p','t.jpg')
with open('model.ini','w') as f:
cp.write(f)
运行结果如下:
image_size
image_width : 300
image_height : 300
image_path
image_path : test.jpg
{'image_width': '300', 'image_height': '300', 'image_path': 'test.jpg'}
[('image_width', '300'), ('image_height', '300')]
---------------写入 部分---------------------
Process finished with exit code 0
最终保存的文件:
argparse
命令行参数
1.0,常用函数
1.1,argparse.ArgumentParser()
创建对象
1.2,parser.add_argument()
向该对象中添加你要关注的命令行参数和选项,每一个add_argument方法对应一个你要关注的参数或选项
参数解释:
dest: 如果提供dest,例如dest=“a”,那么可以通过args.a访问该参数
default: 设置参数的默认值
action: 参数出发的动作
store: 保存参数,默认
store_const: 保存一个被定义为参数规格一部分的值(常量),而不是一个来自参数解析而来的值。
store_ture/store_false: 保存相应的布尔值
append: 将值保存在一个列表中。
append_const: 将一个定义在参数规格中的值(常量)保存在一个列表中。
count: 参数出现的次数
parser.add_argument("-v", “–verbosity”, action=“count”, default=0, help=“increase output verbosity”)
version: 打印程序版本信息
type: 把从命令行输入的结果转成设置的类型
choice: 允许的参数值
parser.add_argument("-v", “–verbosity”, type=int, choices=[0, 1, 2], help=“increase output verbosity”)
help: 参数命令的介绍
1.3,parser.parse_known_args(),parse_args()
parse_args()方法进行解析
parse_known_args()大同小异,在接受多余参数时不报错