Why I can call 'print' from 'eval'

▼魔方 西西 提交于 2019-12-03 03:18:17

The __import__ method is invoked by the import keyword: python.org

If you want to be able to import a module you need to leave the __import__ method in the builtins:

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

obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': {'__import__':__builtins__.__import__}})

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__}})

print works because you specified 'exec' to the compile function call.

import calls the global/builtin __import__ function; if there isn't one to be found, import fails.

print does not rely on any globals to do its work. That is why print works in your example, even though you do not use the available __builtins__.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!