Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 978
Christos Hayward Avatar asked Oct 02 '12 20:10

Christos Hayward


People also ask

Why eval is not working in Python?

The reason it fails is that the functions you import from the math module are not local variables inside the function; they are global. So when you read locals() and insert into the dict, it inserts None for every single one. You would see this if you removed the get(key, None) and just accessed locals()[key] directly.

What can I use instead of eval in Python?

Note: You can also use exec() to dynamically execute Python code. The main difference between eval() and exec() is that eval() can only execute or evaluate expressions, whereas exec() can execute any piece of Python code.

What is eval () function in Python?

The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.

How do you align a string with multiple lines in Python?

The 'Backslash' Method Another alternative for creating multiline strings in Python is by using a backslash ( \ ) to split our string and enclose each line of the string in quote marks.


3 Answers

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
like image 193
Joran Beasley Avatar answered Oct 13 '22 23:10

Joran Beasley


To use such statements with eval you should convert them to code object first, using compile:

In [149]: import os

In [150]: cc = compile('''for index in range(10):
    os.system("echo " + str(index) + "")''','<string>','single')

In [154]: eval cc
--------> eval(cc)
0
Out[154]: 0
1
Out[154]: 0
2
Out[154]: 0
3
Out[154]: 0
4

In [159]: cc = compile("2+2", '<string>', 'single')  # works with simple expressions too 

In [160]: eval cc
--------> eval(cc)
Out[160]: 4
like image 30
Ashwini Chaudhary Avatar answered Oct 13 '22 22:10

Ashwini Chaudhary


We evaluate (eval) expressions, and execute (exec) statements.

See: Expression Versus Statement.

Expression: Something which evaluates to a value. Example: 1+2/x
Statement: A line of code which does something. Example: GOTO 100

like image 32
Andy Hayden Avatar answered Oct 13 '22 23:10

Andy Hayden