对于刚开始使用python的人来说,这是一个很大的困惑,这里的答案有点难以理解,所以我会让它更简单。
当我们指示Python运行我们的脚本时,在我们的代码实际开始处理之前,Python会执行几个步骤:
它被编译为字节码。
然后路由到虚拟机。
当我们执行一些源代码时,Python会将其编译成字节代码。编译是一个转换步骤,字节代码是源代码的底层平台独立表示。
注意,Python字节码不是二进制机器码(例如,英特尔芯片的指令)。
实际上,Python通过将源代码的每个语句分解为单独的步骤,将它们转换为字节码指令。执行字节码转换以加快执行速度。
字节代码的运行速度比原始源代码语句快得多。它有。Pyc扩展,它将被写入,如果它可以写入到我们的机器。
因此,下次我们运行相同的程序时,Python将加载.pyc文件并跳过编译步骤,除非它已被更改。Python自动检查源文件和字节码文件的时间戳,以知道何时必须重新编译。如果我们重新保存源代码,字节码将在下次程序运行时再次自动创建。
如果Python不能将字节代码文件写入我们的机器,我们的程序仍然可以工作。字节码在内存中生成,并在程序退出时简单地丢弃。但是由于.pyc文件加快了启动时间,我们可能希望确保它是为较大的程序编写的。
Let's summarize what happens behind the scenes.
When Python executes a program, Python reads the .py into memory, and parses it in order to get a bytecode, then goes on to execute. For each module that is imported by the program, Python first checks to see whether there is a precompiled bytecode version, in a .pyo or .pyc, that has a timestamp which corresponds to its .py file. Python uses the bytecode version if any. Otherwise, it parses the module's .py file, saves it into a .pyc file, and uses the bytecode it just created.
字节代码文件也是传递Python代码的一种方式。Python仍然会运行一个程序,如果它能找到的都是。Pyc文件,即使原始的.py源文件不在那里。
Python虚拟机(PVM)
Once our program has been compiled into byte code, it is shipped off for execution to Python Virtual Machine (PVM). The PVM is not a separate program. It need not be installed by itself. Actually, the PVM is just a big loop that iterates through our byte code instruction, one by one, to carry out their operations. The PVM is the runtime engine of Python. It's always present as part of the Python system. It's the component that truly runs our scripts. Technically it's just the last step of what is called the Python interpreter.