程序中涉及到了配置文件的操作,虽然比较简单,但随记
configparser 可以完成对配置文件的读取和写入操作,软件启动后首先判断配置文件是否存在 os.path.exists(path),不存在则创建配置文件,分别创建键名和键值,只有在调用 write 函数后才会真正在硬盘上创建文件并写入信息,之后调用read读取文件信息,尽量保证需要读取的键值是存在的。
import configparser # 配置文件操作
class LConfigFile:
""" 配置文件读取/设置 数据库读取/设置 """
def __init__(self):
self.cf = configparser.ConfigParser()
self.cf_path = '' # 配置文件路径
def fun_create_cf(self):
self.cf.add_section('config')
self.cf.set("config", "load_IP", "127.0.0.1")
self.cf.set("config", "server_IP", "127.0.0.1")
self.cf.set("config", "http_port", "8000")
self.cf.write(open(self.cf_path, "w"))
def fun_read_configfile(self, path):
self.cf_path = path + 'config.ini'
if not os.path.exists(self.cf_path): # 如果文件不存在则创建文件
self.fun_create_cf()
# 读取配置文件和数据库
self.cf.read(self.cf_path) # 读取配置文件路径
# 清除字典中的数据
g_config_inf.clear()
# 设置字典
g_config_inf["load_ip"] = self.cf.get('config', 'load_IP') # 读取本地IP
g_config_inf["video_server_ip"] = self.cf.get('config', 'server_IP') # 读物视频服务器IP
g_config_inf["http_port"] = self.cf.getint('config', 'http_port') # 读取http服务器端口
def fun_write_device(self):
self.cf.set("config", "load_IP", g_config_inf["load_ip"])
self.cf.set("config", "server_IP", g_config_inf["video_server_ip"])
self.cf.set("config", "http_port", "%d" % g_config_inf["http_port"])
self.cf.write(open(self.cf_path, "w"))