Question

I have a program, which generates a python program as a string which I then need to execute. However, when I try running the string it throws a syntax error.

For example:

program = "self.move() self.turnRight() if x > 0: self.turnLeft() else: self.turnRight()"

eval(program)

when this runs a syntax error is thrown at whatever the second command is. I'm assuming this is because the string lacks tabs or newlines. Is there a way to automatically add these when the string goes through the eval command?

Was it helpful?

Solution

eval can handle only a single Python expression, and no statement (simple or compound).

Your string contains multiple expressions and statements. You'd have to use exec instead:

program = '''\
self.move()
self.turnRight()
if x > 0:
    self.turnLeft()
else:
    self.turnRight()
'''

exec program

If you were to use a conditional expression you can make it 3 separate expressions:

program = ['self.move()', 'self.turnRight()',
           'self.turnLeft() if x > 0 else self.turnRight']
for line in program:
    eval(program)

Note that it is always a better idea to implement a more specific language rather than re-use Python and eval or exec; you'll create more problems than you'll solve, especially when it comes to security.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top