为什么我可以调用“打印”?来自“评估”
对于代码:
#!/usr/bin/python
src = """
print '!!!'
import os
"""
obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': False})
我得到输出:
!!!
Traceback (most recent call last):
File "./test.py", line 9, in <module>
eval(obj, {'__builtins__': False})
File "", line 3, in <module>
ImportError: __import__ not found
“打印”和“导入”都是语言构造。为什么“eval”限制使用“import”但不限制“print”?
PS 我正在使用 python 2.6
更新:问题不是“为什么导入不起作用?”但是“为什么印刷有用?”是否有一些架构限制或其他限制?
For code:
#!/usr/bin/python
src = """
print '!!!'
import os
"""
obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': False})
I get output:
!!!
Traceback (most recent call last):
File "./test.py", line 9, in <module>
eval(obj, {'__builtins__': False})
File "", line 3, in <module>
ImportError: __import__ not found
Both 'print' and 'import' are language construct. Why does 'eval' restrict using of 'import' but doesn't restrict 'print'?
P.S. I'm using python 2.6
UPDATE: Question is not "Why does import not work?" but "Why does print work?" Are there some architecture restrictions or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
__import__
方法由import
关键字调用:python.org如果您希望能够导入模块,您需要将
__import__
方法保留在内置函数中:The
__import__
method is invoked by theimport
keyword: python.orgIf you want to be able to import a module you need to leave the
__import__
method in the builtins:在您的
eval
中,对import
的调用已成功完成,但是import
使用了内置函数中的__import__
方法,您可以在已在您的exec
中变得不可用。这就是为什么您看到print
不依赖于任何内置函数所以工作正常的原因。您可以从内置函数中仅传递
__import__
,如下所示:In your
eval
the call toimport
is made successfully howeverimport
makes use of the__import__
method in builtins which you have made unavailable in yourexec
. This is the reason why you are seeingprint
doesn't depend on any builtins so works OK.You could pass just
__import__
from builtins with something like:print 之所以有效,是因为您在
compile
函数调用中指定了'exec'
。print works because you specified
'exec'
to thecompile
function call.import
调用全局/内置的__import__
函数;如果找不到,导入
就会失败。print
不依赖任何全局变量来完成其工作。这就是为什么print
在您的示例中起作用,即使您不使用可用的__builtins__
也是如此。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 whyprint
works in your example, even though you do not use the available__builtins__
.