1

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?

2
  • Out of curiosity: how are you generating the program? Commented Apr 7, 2014 at 15:24
  • a variant of genetic programming Commented Apr 7, 2014 at 15:28

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So throwing a ; in between each expression doesn't jive?
@wnnmaw: no, because that's still multiple expressions. That's quite apart from including a statement like if.
Thanks for the answer, is there anyway to add the newlines and tab's in awell as exec still throws a syntax error./
@ChrisHeadleand: Not automatically, no. Code meaning changes entirely based on where indentation and newlines are used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.