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,
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.
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.
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With