I have created a .ini-like file with all the values which I need later in my program, see below:
[debugging]
checkForAbort = 10
...
[official]
checkForAbort = 30
...
I would like to read all these items into a single class and make it accessible from other parts of my python project.
What I have so far is the code below:
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
I am new to python but I can still see lots of problem with my code:
- I am forced to add a attribute for each item in my class file. and keep the configuration file and my class in sync all the time.
- This class is not a singleton, therefore the reading/parsing will be done from wherever it is imported!
- If a value is added to the config-file with is not defined in my class, it will probably crash!
How should I solve this problem instead? Can class attributes be created dynamically?
My class only need to read from the values, so no writing to the configuration file is needed!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…