0

If I have a string containing some code in a python file. I want to run the code in the string, for example:

program = "for i in range(100):\n\tprint(i)"
eval(program)

However, I'm pretty sure eval only works for mathematical operations, so it throws a syntax error:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    eval(program)
  File "<string>", line 1
    for i in range(100):
      ^
SyntaxError: invalid syntax

Is there a way in python of running code contained in a string?

2
  • 2
    Strictly speaking, the answer to the question in the title is to use compile; exec produces the code and executes it. Commented Dec 2, 2019 at 16:57
  • 1
    possible duplicate: stackoverflow.com/questions/701802/… Commented Dec 2, 2019 at 16:58

2 Answers 2

6

Yes, eval() only evaluates expressions, not statements or suites (which comprise full Python programs).

You're looking for the exec() function.

exec("for i in range(100):\n\tprint(i)")

However, do remember you usually don't need eval() or exec(), and especially you'll never want to exec() or eval() user input.

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

1 Comment

this is clearly a duplicate. you've been around long enough to know to mark it as one...
0

Use the exec() function.

program = "for i in range(100):\n\tprint(i)"
exec(program)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.