Why I can call 'print' from 'eval'

前端 未结 4 584
夕颜
夕颜 2021-02-06 09:15

For code:

#!/usr/bin/python

src = \"\"\"
print \'!!!\'
import os
\"\"\"

obj = compile(src, \'\', \'exec\')
eval(obj, {\'__builtins__\': False})
4条回答
  •  轮回少年
    2021-02-06 09:59

    In your eval the call to import is made successfully however import makes use of the __import__ method in builtins which you have made unavailable in your exec. This is the reason why you are seeing

    ImportError: __import__ not found
    

    print doesn't depend on any builtins so works OK.

    You could pass just __import__ from builtins with something like:

    eval(obj, {'__builtins__' : {'__import__' :__builtins__.__import__}})
    

提交回复
热议问题