forked from offu/WeRoBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
46 lines (35 loc) · 1.06 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding: utf-8 -*-
import imp
class ConfigAttribute(object):
"""
让一个属性指向一个配置
"""
def __init__(self, name):
self.__name__ = name
def __get__(self, obj, type=None):
if obj is None:
return self
rv = obj.config[self.__name__]
return rv
def __set__(self, obj, value):
obj.config[self.__name__] = value
class Config(dict):
def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名。
"""
d = imp.new_module('config')
d.__file__ = filename
with open(filename) as config_file:
exec (compile(config_file.read(), filename, 'exec'), d.__dict__)
self.from_object(d)
return True
def from_object(self, obj):
"""
在给定的 Python 对象中读取配置。
:param obj: 一个 Python 对象
"""
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)