python - 需要澄清 python 中 exec 的用法

标签 python

我有这个:

>>> d = {}
>>> d["hi"] = 12345

>>> d1 = {}

>>> d1["hiiii"] = 1234590

我知道为什么会出现下面的错误。这是因为 exec 找不到变量 hi 和 hiiii。

>>> exec "print hi, hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hi' is not defined


>>> exec "print hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hiiii' is not defined

现在它可以工作了,因为 exec 能够在字典 d 和 d1 中找到 hi 和 hiiii 变量

>>> exec "print hi, hiiii" in d , d1
12345 1234590

到目前为止一切顺利。

问题:

现在,当我打印 d 时,我看到它已被修改并打印了很多键、值对..为什么? 但是在打印 d1 时我没有看到很多键、值对,为什么会这样?

最佳答案

这在 the docs 中有解释。 :

As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module __builtin__ under the key __builtins__ (!).

关于python - 需要澄清 python 中 exec 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730518/

相关文章:

python - 在 Fabric(Python 库)中如何访问子程序中的 IP/主机名?

python - Python 中的进度条和组合

python - 如何根据pandas数据框中变量的变化删除行

python - Matplotlib 中的字幕对齐问题

python - LSTM - 对部分序列进行预测

python - 确定是否可以从类或实例调用可调用对象

python - 将 Python Pandas DataFrame 写入 Word 文档

python - python中根据名称对文件进行排序

python - 根据另一个列表的内容从一个列表中删除项目

Python 日志记录 : create log if not exists or open and continue logging if it does