你可以从python中重新分配__builtins__恢复吗?

Har*_*mha 26 python cpython

如果我打开交互模式并输入:

__builtins__ = 0 # breaks everything
Run Code Online (Sandbox Code Playgroud)

我完全打破了会议?如果是这样,幕后发生了什么,将__builtins__分配给内置模块,而解释器无法处理?如果没有,我该如何从中恢复?

我自己尝试修复它的一些尝试:

  • 任何导入任何内容的尝试都会导致错误"找不到ImportError __import__"
  • 我可能用来做除评估数字表达式以外的任何其他函数都被破坏了
  • 还有另一个变量__package__仍可访问,但我不知道是否可以使用它.

Ned*_*der 30

您通常可以访问所需的任何内容,即使__builtins__已被删除.这只是一个挖掘足够远的问题.例如:

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> __builtins__ = 0
>>> open
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'open' is not defined
>>> dir
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dir' is not defined
>>> int
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'int' is not defined
>>> float
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'float' is not defined
>>>
>>> __builtins__ = [t for t in ().__class__.__bases__[0].__subclasses__() if 'warning' in t.__name__][0]()._module.__builtins__
>>>
>>> open
<built-in function open>
>>> int
<type 'int'>
>>> float
<type 'float'>
>>>
Run Code Online (Sandbox Code Playgroud)

为了解释这里发生了什么,读Eval真的很危险,使用类似的技术来证明你不能安全地执行不受信任的Python代码.

  • @ acjohnson55,怎么样`__builtins __.__ dict __.clear()`.我试过了,现在我的外壳太破了,甚至都没有尝试执行我给它的东西. (6认同)
  • @HartSimha:如果当前帧中的builtins与内置解释器不同,Python 2将启用受限模式.由于在Python 3中删除了限制模式,因此很容易修改这个答案以从函数中获取`__builtins__`:`__ builtin__ = [t for t in().__ class __.__ base __.__ subclasses __()if t .__ name__ =='Sized '] [0] .__ LEN __.__全局__ [' __建宏__']`. (4认同)