#coding=UTF-8
#通过configparser模块读取ini配置文件的数据
from configparser import ConfigParser
from framework_Var_A.var_A import *
class ParseIni:
def __init__(self):
# 创建配置文件解析器对象
self.conf = ConfigParser()
# 获取elements_A.ini配置文件的路径
self.ini_path = ini_path
# 读取配置文件
self.conf.read(ini_path)
self.sections = self.conf.sections()
print(' ')
print('获取配置文件所有的section', self.sections)
def options(self):
self.option = self.conf.options(self.sections[0])
print('获取指定section下所有option',self.option)
return self.option
def items(self):
#返回的列表格式
self.items = self.conf.items(self.sections[0])
print('获取指定section下所有的键值对', self.items)
return self.items
def dict_items(self):
#返回的字典格式
self.dict_items = self.conf.items(self.sections[0])
print('获取指定section下所有的键值对(字典格式)', dict(self.dict_items))
return self.dict_items
def value(self):
self.options()
#返回的字符串类型
self.value = self.conf.get(self.sections[0], self.option[0])
print("获取指定section下键option的属性值:" + self.value, type(self.value))
return self.value
if __name__=='__main__':
ParseIni().options()
ParseIni().items()
ParseIni().dict_items()
ParseIni().value()
# getint(section,option) 返回int类型
# getfloat(section, option) 返回float类型
# getboolean(section,option) 返回boolen类型
执行结果
"C:\Program Files\Python37\python.exe" D:/PycharmProjects/keyword_driver_framework/util_A/parseini.py
D:\PycharmProjects\keyword_driver_framework\Data_A\126邮箱联系人.xlsx
获取配置文件所有的section ['login', 'index', 'add_contact']
获取指定section下所有option ['frame', 'username', 'passwd', 'loginbutton']
获取配置文件所有的section ['login', 'index', 'add_contact']
获取指定section下所有的键值对 [('frame', 'id>x-URS-iframe'), ('username', "xpath>//input[@name='email']"), ('passwd', "xpath>//input[@name='password']"), ('loginbutton', 'id>dologin')]
获取配置文件所有的section ['login', 'index', 'add_contact']
获取指定section下所有的键值对(字典格式) {'frame': 'id>x-URS-iframe', 'username': "xpath>//input[@name='email']", 'passwd': "xpath>//input[@name='password']", 'loginbutton': 'id>dologin'}
获取配置文件所有的section ['login', 'index', 'add_contact']
获取指定section下所有option ['frame', 'username', 'passwd', 'loginbutton']
获取指定section下键option的属性值:id>x-URS-iframe <class 'str'>
Process finished with exit code 0
ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。
注意:在python 3 中ConfigParser
模块名已更名为configparser