python 读取 ini 配置文件
关于读取配置文件的想法 主要是因为程序里面通过改变变量值 达到不同的目的
如果写死 变成常量 如果下次领导说换一个玩法 还得去改代码 再重新编译一次
开发过程中发现较关键的变量 最好是把它配置化 当然如果你来了 肯定也是为此
进入正题
config.ini
[test]
addr = https://172.16.101.46:8888
[test2]
addr = https://172.16.101.46:9999
写一个DEMO:
import configparser
config = configparser.ConfigParser() # 类实例化
path = './config.ini' # 定义文件路径config.read(path)
section = config.sections() # 读取文件中所有节点
print(section)node = config.items('path') # 读取指定节点下的所有项
print(node)value = config.get('test', 'addr') # 读取指定节点下的某个项
print(value)
最后抽象成类便于以后使用,源码如下:
import configparser import logging class Read_ini: def __init__(self, path='./config.ini'): try: # 读取配置 self.cfg = configparser.ConfigParser() self.cfg.read(path, encoding='utf-8') except Exception as e: msg = "读取ini错误:" + str(e) logging.error(msg) def get_sections(self): """获取所有节点[xxx]""" try: sections = self.cfg.sections() return sections except Exception as e: msg = "未找到节点:" + str(e) logging.error(msg)
def get_node(self,node): """获取节点下所有元素""" try: section = self.cfg.items(node) return section except Exception as e: msg = "未找到节点:" + str(e) logging.error(msg)
def get_value(self, node, key): """获取元素值""" try: value = self.cfg.get(node, key) return value except Exception as e: msg = "未找到元素:" + str(e) logging.error(msg)
参考: https://www.cnblogs.com/XhyTechnologyShare/p/11935553.html
浙公网安备 33010602011771号