I have the following code, which uses the eval function:
lines = self.fulltext.splitlines()
CURRENT = 0
extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"),
                       "ground pressure" : (CURRENT, 2, "self.ground_pressure")                     
             }
print locals()
for line in lines:
    for label, details in extractors.iteritems():
        if label in line:
            if details[0] == CURRENT:
                values = line.split()
                eval("%s = values[%d]" % (details[2], details[1]))
However, when I run it I get the following error:
eval("%s = values[%d]" % (details[2], details[1]))
  File "<string>", line 1
    self.solar_z = values[1]
                 ^
SyntaxError: invalid syntax
Why is this? self.solar_z is defined, and the statement that is eval'd looks correct.
Use exec instead, it does evaluate statements, to.
exec "self.solar_z = values[1]" in locals(), locals()
eval() evaluates expressions. Assignment in Python is a statement. This will not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With