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?

AKX
  • 152,115
  • 15
  • 115
  • 172
  • 2
    Strictly speaking, the answer to the question in the title is to use `compile`; `exec` produces the code *and* executes it. – chepner Dec 02 '19 at 16:57
  • 1
    possible duplicate: https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python – natka_m Dec 02 '19 at 16:58

2 Answers2

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.

AKX
  • 152,115
  • 15
  • 115
  • 172
0

Use the exec() function.

program = "for i in range(100):\n\tprint(i)"
exec(program)
Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54