configparser库是Python的一个内置库,用于处理配置文件。它提供了一个类似于字典的接口,可以方便地读取和写入INI格式的配置文件。
def token_reset():
# 初始化根据ini配置文件批量获取TOKEN
config = configparser.ConfigParser()
config.read(TOKEN_INI, encoding='utf-8-sig') # 指定编码为utf-8-sig
for section in config:
if section != 'DEFAULT':
data = dict(config.items(section))
get_token(section,data)
logger.debug(f"************批量获取Token完成************")
return 0
def read_config(filename, section):
# 根据运营商名称获取transid
try:
# 创建一个ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件,指定编码为utf-8-sig
config.read(filename, encoding='utf-8-sig')
# 检查指定的section是否存在于配置文件中
if section in config:
# 获取section下的所有键值对,并将其转换为字典
transid = dict(config.items(section))
return transid
else:
# 如果section不存在,记录错误日志并返回1
logger.error(f"{filename}没找到:{section}")
return 1
except Exception as e:
# 如果发生异常,记录错误日志并返回1
logger.error(f"{filename}没找到:{section}-{e}")
return 1
def update_tokenini_data(section, key, value):
# 使用锁确保线程安全
with ini_lock:
try:
# 创建一个ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
config.read(TOKEN_RSP)
# 如果配置文件中不存在指定的section,则添加该section
if not config.has_section(section):
config.add_section(section)
# 设置指定section下的key-value对
config.set(section, key, value)
# 将修改后的配置写回文件
with open(TOKEN_RSP, 'w') as configfile:
config.write(configfile)
except Exception as e:
# 记录错误日志
logger.error(f"{e}")
# 如果配置文件中存在指定的section,尝试删除并重新添加
if config.has_section(section):
try:
config.remove_section(section)
config.add_section(section)
config.set(section, key, value)
with open(TOKEN_RSP, 'w') as configfile:
config.write(configfile)
except Exception as e2:
# 记录错误日志
logger.error(f"Failed to replace section and key-value pair: {e2}")