Home >Backend Development >Python Tutorial >How python runs code
As a dynamic language, python is actually an interpreter software package.
When Python runs a script, Python also performs a few steps before the code starts processing. (Recommended learning: Python video tutorial)
The first step is to compile into so-called "bytecode". If the Python process has write permission, the bytecode of the program will be saved For a file with a .pyc extension, if Python cannot write the bytecode on the machine, the program will still work: the bytecode will be generated in memory and simply discarded when the program ends. Once the program is compiled into bytecode (or the bytecode is loaded from an existing .pyc file), the subsequent bytecode is sent to what is often called the Python Virtual Machine (PVM for short) for execution.
The written py file is first translated into a bytecode file (hidden suffix pyc), and then the bytecode is automatically compiled using PVM (virtual machine), and then interpreted to the hardware.
If a pyc file has already been formed, then your py file has not been changed. When the machine reinterprets it, it will skip the bytecode translation step. First check your .py and .pyc File timestamp, if it has not been modified, run the pyc file directly, otherwise the bytecode will be re-translated.
PVM is not an independent program, it is the running engine of Python and does not require installation. In fact, PVM is a large loop that iteratively runs bytecode instructions, completing operations one after another.
So Python has more dynamic language features: at runtime, it is possible for a Python program to build and execute another Python program, and it is often very convenient. For example, the eval and exec built-in modules accept and run strings containing Python program code. Use the following code to view the bytecode of the add function:
import dis def add(a,b): sum=a+b return sum print(dis.dis(add))
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How python runs code. For more information, please follow other related articles on the PHP Chinese website!