pyhton自动化经常要读取配置文件,封装一个类方便以后读取
现有配置文件如下:
[Login]
username = id>username
password = id>password
login = xpath>//span[text()='登 录']/..
overview = xpath>//li/span[text()='总览']
pic_code = id>canvas1
code = xpath>//input[@id="code"]
封装类:
import configparser
class ConfigUtil(object):
def __init__(self, path):
self.path = path
self.cf = self.load_init(self.path)
def load_init(self, path):
cf = configparser.ConfigParser()
cf.read(path, encoding='utf-8')
return cf
# 获取文件所有的sections
def get_sections(self):
secctions = self.cf.sections()
return secctions
# 获取某个section所对应的键
def get_options(self, section):
options = self.cf.options(section)
return options
# 获取某个section所对应的键值对
def get_items(self, section):
items = self.cf.items(section)
return items
# 获取某个section某个key所对应的value
def get_value(self, section, key):
value = self.cf.get(section, key)
return value
if __name__ == '__main__':
path = r'E:/Project/untitled/EsageUI/config/login.ini'
section = 'Login'
key = 'password'
config = ConfigUtil(path)
print(config.get_sections())
print(config.get_options(section))
print(config.get_items(section))
print(config.get_value(section, key))