我已经创建了一个类似 .ini 的文件,其中包含我稍后在程序中需要的所有值,见下文:
[debugging]
checkForAbort = 10
...
[official]
checkForAbort = 30
...
我想将所有这些项目读取到一个类中,并使其可以从我的 python 项目的其他部分访问。 到目前为止,我所拥有的是以下代码:
from ConfigParser import SafeConfigParser
import glob
class ConfigurationParameters
def __init__(self):
self.checkForAbortDuringIdleTime = None
parser = SafeConfigParser()
# making a list here in case we have multiple files in the future!
candidatesConfiguration = ['my.cfg']
foundCandidates = parser.read(candidatesConfiguration)
missingCandidates = set(candidatesConfiguration) - set(found)
if foundCandidates:
print 'Found config files:', sorted(found)
else
print 'Missing files :', sorted(missing)
print "aborting..."
# check for mandatory sections below
for candidateSections in ['official', 'debugging']:
if not parser.has_section(candidateSections)
print "the mandatory section", candidateSections " is missing"
print "aborting..."
for sectionName in ['official', 'debugging']:
for name, value in parser.items(section_name):
self.name = value
我是 python 的新手,但我的代码仍然存在很多问题:
- 我不得不为我的类文件中的每个项目添加一个属性。并始终保持配置文件和我的类同步。
- 这个类不是单例,因此读取/解析将从导入的任何地方完成!
- 如果在我的类中没有定义的值被添加到配置文件,它可能会崩溃!
我应该如何解决这个问题?类属性可以动态创建吗?
我的类只需要读取值,所以不需要写入配置文件!
请您参考如下方法:
另外,你可以这样做like Alex Martelli does in his Bunch class :
文件MyConfig.py:
from ConfigParser import SafeConfigParser
section_names = 'official', 'debugging'
class MyConfiguration(object):
def __init__(self, *file_names):
parser = SafeConfigParser()
parser.optionxform = str # make option names case sensitive
found = parser.read(file_names)
if not found:
raise ValueError('No config file found!')
for name in section_names:
self.__dict__.update(parser.items(name)) # <-- here the magic happens
config = MyConfiguration('my.cfg', 'other.cfg')
文件foo.py:
from MyConfig import config
# ...
文件MyProgram.py:
from MyConfig import config
print config.checkForAbort
import foo
assert config is foo.config
Python Language Reference声明 "导入语句分两步执行:(1) 找到一个模块,并在必要时对其进行初始化;(2) 在本地 namespace (导入语句出现的范围)中定义一个或多个名称。 "
这意味着,当一个模块被导入时,一个或多个本地名称被绑定(bind)到一个模块对象,并且只有在 Python 程序运行时第一次导入它时它才会被初始化(即从文件中读取并运行)。
在上面的代码中,名称 config 只是一个本地名称,它指的是模块对象的一个属性。模块对象在 MyProgram 中被引用时(通过 from MyConfig import config)已被 Python 解释器初始化。当 MyProgram 导入 foo 时,它已经初始化并绑定(bind)到模块 foo 和 MyProgram 中的本地名称,我们可以将其称为 foo.config。但是这两个名称指的是非常相同的对象。
