在很多的脚本中的编写中,都有涉及到配置文件的读取,这些配置文件为ini,conf,等格式
实则都是以文本的形式来存在的,为什么需要这些配置文件呢?在脚本的编写中,某一些参数配置每次使用的时候不一样
每个人使用的时候也不一样,无非有几种形式
1.直接写死在脚本中是不行的,这显然是不行的
2.不写死的情况分别存在在各个不同的py文件中,修改起来不直观,麻烦,对不同的人来说都需要去寻找这个位置
3.另外是将文件打包成了exe,无法修改里面的参数了,那么使用用户输入来实现参数的变化,但是当参数众多时,不方便
4.exe文件每次运行都需要输入参数导致不友好
所以,将脚本中所有的配置文件信息全部抽离出来到一个或者多个配置文件中来统一读取修改,而且还能加入注释,方便
Configparser模块用于处理特定格式的文件,其本质上是利用open来操作文件
配置文件格式:
[section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值
实际上就是将一个特定格式的文本文件,使用特定的格式来定义其中的参数读取
封装一个配置文件读取的类,同一来读取配置文件,‘#’号用于编写注释
配置文件格式如下:
[CONFIG] #SSH的ip,端口,账号,密码定义 host = 10.6.161.252 port = 22 username = root password = superwifi
#coding:utf-8 from configparser import ConfigParser class Configinfo(): def __init__(self,config_file): config = ConfigParser() config.read(config_file,encoding='utf-8') try: self.host = config.get('CONFIG','host') self.port = config.get('CONFIG','port') self.username = config.get('CONFIG','username') self.password = config.get('CONFIG','password') except Exception as e: print '读取发生错误:%s'%e exit() def get_host(self): return self.host def get_port(self): return self.port def get_username(self): return self.username def get_password(self): return self.password if __name__ == '__main__': config = Configinfo('test.ini') info = (config.get_host(),config.get_port(),config.get_username(),config.get_password())
configparser模块的相关操作方法
1、获取所有节点 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret = config.sections() print(ret)
2、获取指定节点下所有的键值对 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret = config.items('section1') print(ret)
3、获取指定节点下所有的建 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret = config.options('section1') print(ret)
4、获取指定节点下指定key的值 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') v = config.get('section1', 'k1') # v = config.getint('section1', 'k1') # v = config.getfloat('section1', 'k1') # v = config.getboolean('section1', 'k1') print(v)
5、检查、删除、添加节点 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') # 检查 has_sec = config.has_section('section1') print(has_sec) # 添加节点 config.add_section("SEC_1") config.write(open('xxxooo', 'w')) # 删除节点 config.remove_section("SEC_1") config.write(open('xxxooo', 'w'))
6、检查、删除、设置指定组内的键值对 import configparser config = configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') # 检查 has_opt = config.has_option('section1', 'k1') print(has_opt) # 删除 config.remove_option('section1', 'k1') config.write(open('xxxooo', 'w')) # 设置 config.set('section1', 'k10', "123") config.write(open('xxxooo', 'w'))