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?
-
Out of curiosity: how are you generating the program?Hugh Bothwell– Hugh Bothwell2014年04月07日 15:24:24 +00:00Commented Apr 7, 2014 at 15:24
-
a variant of genetic programmingChris Headleand– Chris Headleand2014年04月07日 15:28:34 +00:00Commented Apr 7, 2014 at 15:28
1 Answer 1
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.
4 Comments
; in between each expression doesn't jive?if.