我刚刚看了Philip Guo的this Youtube lecture关于CPython内部的文章,我对一件事感到困惑。你知道吗
在25:55,他修改了CPython的C源代码,在运行所有字节码指令的无休止循环的开始处插入printf(“hello\n”)
;您可以通过以下方法执行相同的操作:
Python/ceval.c
for (;;) {
printf('hello\n');
作为无尽循环的第一行。你知道吗configure
和make
构建Python二进制文件。你知道吗他写了三行字测试.py地址:
X = 1
Y = 2
print X + Y
问题是,当他跑的时候测试.py有了经过修改的解释器,为什么在我们看到“3”之前会有这么多“你好”?你知道吗
三行代码应该编译成几个字节码指令,加载值1,加载值2和调用print的指令,所以我可以想象当它执行从测试.py,我们应该只看到几个“你好”。你知道吗
那么编译器在编译外部Python脚本之前实际上会生成许多内部字节码指令?你知道吗
有两个原因让你看到这么多
hello
的印刷品:-v
开关运行常规的Python解释器来查看每次导入的内容。每个模块都由多个语句组成,因此在进入正在运行的小脚本之前,需要经历相当多的字节码。你知道吗如果我将这3行代码放到
test.py
中,并使用未修改的python2.7二进制代码运行它,使用-v
开关,我会看到:每个
import ...
行引用一个内置模块(Python二进制文件的一部分,用C实现)或.pyc
字节码缓存文件。在脚本代码运行之前,有17个这样的文件被导入。你知道吗主脚本中的3行代码转换为另外9个字节码指令:
(我忽略了末尾的2个字节码,编码了一个额外的
return None
,它实际上不适用于一个模块)。你知道吗相关问题 更多 >
编程相关推荐