Why I can call 'print' from 'eval'

前端 未结 4 524
夕颜
夕颜 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 10:00

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

提交回复
热议问题