Search code examples
pythonpython-3.xmetaprogrammingeval

Why is Python's eval() rejecting this multiline string, and how can I fix it?


I am attempting to eval the following tab-indented string:

'''for index in range(10):
        os.system("echo " + str(index) + "")
'''

I get, "There was an error: invalid syntax , line 1"

What is it complaining about? Do I need to indent to match the eval() statement, or write it to a string file or temp file and execute that, or something else?

Thanks,


Solution

  • eval evaluates stuff like 5+3

    exec executes stuff like for ...

    >>> eval("for x in range(3):print x")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        for x in range(3):print x
          ^
    SyntaxError: invalid syntax
    >>> exec("for x in range(3):print x")
    0
    1
    2
    >>> eval('5+3')
    8