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
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:
and
Do NOT use this to execute untrusted user-supplied text.
eval()
andexec
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.