Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

python - Eval not working on multi-line string

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...