开发者

eval giving syntax error even when correct code given

开发者 https://www.devze.com 2023-03-14 00:34 出处:网络
I have the following code, which uses the eval function: lines = self.fulltext.splitlines() CURRENT = 0

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消