- 目的
一、练习类使用
二、练习配置文件操作 - config.ini
[login]
uname = root
passwd = 123456
[test]
a = 2
b = 3
[my]
dd = sd
gg = 个
[del]
a=dcds
cs=sdcsd
- config.py
import os
import sys
try:
import configparser
except Exception as e:
sys.exit("pip install configparser")
try:
from configobj import ConfigObj
except Exception as e:
sys.exit("pip install configobj")
class Config(object):
"""
@ 操作配置文件
@ fname : 操作文件名称(必需)
@ option : 配置文件中的项 eg:[DEFAULT]
@ name : 配置项的key
@ value : 配置项的value
@ option_content : 写入新项所需 eg:{'key':'value'}
"""
def __init__(self, fname, option='', name='', value='', option_content={}):
curpath = os.path.dirname(os.path.realpath(__file__))
self._path = os.path.join(curpath, fname)
self.conf = configparser.ConfigParser()
self.option = option
self.name = name
self.value = value
self.option_content = option_content
def get_sections(self):
'''
@ return : list
'''
conf = self.conf
try:
conf.read(self._path, encoding='utf-8')
except Exception as e:
print(e)
sys.exit(self._path + "不存在或权限不足")
sections = conf.sections()
return sections
def _read(self):
try:
conf = ConfigObj(self._path, encoding='utf-8')
except Exception as e:
print(e)
sys.exit(self._path + "不存在或权限不足")
else:
return conf
def get_options(self):
'''
@ param :
option : string
@ return : dict
'''
conf = self._read()
try:
res = conf[self.option]
return res
except Exception as e:
print(e)
sys.exit(self.option + "不存在")
def set_options(self):
'''
@ param :
option : string
option_content : dict
@ return : bool
'''
conf = self._read()
try:
conf[self.option] = {}
for k,v in self.option_content.items():
conf[self.option][k] = v
conf.write()
return True
except Exception as e:
print(e)
sys.exit(self.option + "添加失败")
def del_options(self):
'''
@ param :
option : string
@ return : bool
'''
conf = self._read()
try:
del conf[self.option]
conf.write()
return True
except Exception as e:
print(e)
sys.exit(self.option + "删除失败")
def config_read(self):
'''
@ param :
option : string
name : string
@ return : string
'''
conf = self._read()
try:
res = conf[self.option][self.name]
return res
except Exception as e:
print(e)
sys.exit(self.option + '>' + self.name + "不存在")
def config_del(self):
'''
@ param :
option : string
name : string
@ return : bool
'''
conf = self._read()
try:
del conf[self.option][self.name]
return True
except Exception as e:
print(e)
sys.exit(self.option + '>' + self.name + "删除失败")
def config_set(self):
'''
@ param :
option : string
name : string
value : string
@ return : bool
'''
conf = self._read()
try:
conf[self.option][self.name] = self.value
conf.write()
return True
except Exception as e:
print(e)
sys.exit(self.option + '>' + self.name + "删除失败")
if __name__ == '__main__':
test = Config('config.ini')
print(test.get_sections())