Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eval not working on multi-line string

Tags:

python

eval

I am having issues with executing a multi-line string with the python eval function/

code = ''' 

def main():
  print "this is a test"

main()

'''

eval(code)

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    eval(code)
  File "<string>", line 3
    def main():
      ^
SyntaxError: invalid syntax
like image 988
John Galt Avatar asked Jun 05 '15 16:06

John Galt


People also ask

Does eval work on strings?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.

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 is the difference between eval () and int () function?

eval evaluates any python code. int tries to convert any type to integer (float, bool, string ...). you got it.

What is exec () and eval ()?

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.


1 Answers

eval can only evaluate Python expressions, not statements. A function definition is a statement, not an expression.

Use exec to execute Python statements.

See the Top-level components document, which differentiates (among others) between file input and expression input:

file_input ::=  (NEWLINE | statement)*

This syntax is used in the following situations:

[...]

  • when parsing a string passed to the exec statement;

and

[...] The string argument to eval() must have the following form:

eval_input ::=  expression_list NEWLINE*

Do NOT use this to execute untrusted user-supplied text. eval() and exec are not guarded against malicious users, and they can and will take over the web process if you use this.

In fact, there is no 'safe' way to ever do this, other than running the code in a throw-away virtual machine with all services firmly bolted shut. Run a new virtual machine for new code, throw away the whole VM when done or after a timeout.

like image 88
Martijn Pieters Avatar answered Sep 25 '22 23:09

Martijn Pieters