import os
import configparser #引入模块
config = configparser.ConfigParser() #类中一个方法 #实例化一个对象 #后面的ConfigParser中的C和P是大写
config["DEFAULT"] = {'ServerAliveInterval': '45>123',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11':'yes'
} #类似于操作字典的形式
config['bitbucket.org'] = {'User':'Atlan'} #类似于操作字典的形式
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:
config.write(configfile) #将对象写入文件
data = config.get("DEFAULT","ServerAliveInterval")
data = data.split(">")
print(data)
输出:
[‘45’, ‘123’]
[DEFAULT]
serveraliveinterval = 45>123
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = Atlan
[topsecret.server.com]
host port = 50022
forwardx11 = no
封装直接调用
coding=utf-8
import configparser
import os
class Read_Ini(object):
"""
读取配置文件
"""
def __init__(self):
"""
声明这个类的时候,就要传入配置文件的地址和节点
:param node: 配置中选取的节点
:param file_name: 配置文件的地址.
"""
# if file_name == None:
# file_name = r"D:\ruleUI\config\LocalElement.ini"
# self.node = node
# self.cf = self.load_ini(file_name)
pass
def load_ini(self, file_name=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_name.ini')):
"""
读取配置文件
os.path.abspath(__file__):当前文件的绝对路径
dirname(os.path.abspath(__file__)):当前路径的上一级
os.path.dirname(os.path.abspath(__file__))#当前路径上一级的绝对路径
:param file_name: 配置文件的地址
:return:
"""
cf = configparser.ConfigParser()
cf.read(file_name, encoding="utf-8")
return cf
# 获取用户的姓名,和密码
# 不同的环境,需要更换node值
def get_value(self, env, key):
"""
:param node 对应的是配置文件中的节点
:param key: 配置文件中页面元素对应的名称
:return: 元素的选取方式和元素数据.
"""
data = self.load_ini().get(env, key)
data = data.split(">")
return data
if __name__ == '__main__':
read_init = Read_Ini()
print(read_init.get_value("uat", "张飞")[1]
[uat]
张飞 = 18955565>88888888
关羽 = 1891256>123456>USER180301007