Out of the box, no, you can't do this with ConfigParser
. However, ConfigParser.ConfigParser
is just a class, and classes are overrideable :). I see no reason why you couldn't write a class FormulaConfigParser(ConfigParser)
that overrides ConfigParser.get()
to implement this behaviour, or perhaps adds a .getformula()
method?
Is there any way to use ConfigParser to evaluate formulas rather than interpolate strings?
-
30-05-2022 - |
Frage
I'm using ConfigParser in python 2.7.5 to parse a configuration file. I would like to interpolate some values but treat them as integers rather than strings (i.e., do the calculations). Is this possible?
Here's how I'm doing it currently:
global constantValues
config = ConfigParser.ConfigParser()
# use ConfigParser to get values
config.read("filename")
for section in config.sections():
if (section == "INT"):
for option in config.options(section):
constantValues[option] = config.getint(section, option)
elif (section == "BOOL"):
for option in config.options(section):
constantValues[option] = config.getboolean(section, option)
elif (section == "FLOAT"):
for option in config.options(section):
constantValues[option] = config.getfloat(section, option)
else:
for option in config.options(section):
constantValues[option] = config.get(section, option)
constantValues["samp_per_clk"] = int (constantValues["fs"] / constantValues["sys_clk"])
constantValues["samp_per_trig"] = float(constantValues["fs"] / constantValues["sys_clk"] * constantValues["clks_per_enc"])
I'd like to calculate "samp_per_clk" and "samp_per_trig" in the config file and then use the configparser to read it in. Something like this:
samp_per_clk: %(fs) / %(sys_clk)
But everything I've read seems to say you can only interpolate with strings. Am I missing anything?
EDIT: Based on Paul Woolcock's answer below, and the answer to this question, I added the following wrapper class:
class myConfigParser(object):
def __init__(self, origobj):
self.myobj = origobj
def getFormula(self, section, option):
retString = self.get(section, option)
return eval(retString)
def __getattr__(self, attr):
return getattr(self.myobj, attr)
That did the trick!!
Lösung
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow