28

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

__builtins__ = 0 # breaks everything

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

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

  • 任何导入任何内容的尝试都会导致错误“ImportError __import__ not found”
  • 除了评估数值表达式之外,我可能用来做任何事情的所有函数都被破坏了
  • 还有另一个变量 __package__ 仍然可以访问,但我不知道是否/如何使用它。
4

3 回答 3

31

您通常可以访问您需要的任何内容,即使__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'>
>>>

要了解这里到底发生了什么,请阅读Eval 确实很危险,其中使用了类似的技术来证明您无法安全地执行不受信任的 Python 代码。

于 2012-11-09T11:39:08.953 回答
3

基本上弄乱受保护和保留的名称意味着中断您的会话,有时无法从中恢复。

例如,您可以输入 shell:

True = False # The chaos begins!

这些在其他编程语言中是不可能的,但是 python 可以让你做你想做的事,即使它会破坏一切。

于 2012-11-09T11:30:01.430 回答
3

你是对的; 您实际上可以中断 Python 会话。我怀疑有没有办法完全摧毁它——看到内德的回答对我来说是一个很大的启示。

作为一种非常动态的语言,Python 为您提供了很多可以吊死自己的绳索。但是,不要将其视为缺陷;一个常见的 Python 口号是“我们在这里都是成年人”。如果你理解这门语言并且真的知道你在做什么,那么你基本上可以对 Python 的各个方面进行疯狂的控制。

于 2012-11-09T11:42:12.827 回答