I. What Is the Execution Flow of a Python Program
The execution flow of a Python program refers to the series of processing steps that Python code goes through from the moment it is written to the point where it ultimately produces a running result.
For example, writing a simple program:
name = "Python"
print(f"Hello, {name}!")
Running it:
python hello.py
The final output:
Hello, Python!
On the surface, the program only executes two lines of code, but internally the interpreter needs to complete multiple steps:
- Locate and read the Python source code file.
- Perform lexical analysis and syntax analysis on the source code.
- Organize the code into an abstract syntax tree (AST).
- Compile the abstract syntax tree into bytecode.
- Create the required for program execution.
- Execute the bytecode by the virtual machine.
- Create objects, bind variables, and call functions.
- Write the results to standard output.
- Program execution ends and releases related resources.
Note that the above flow mainly describes the typical execution mechanism of CPython. Python is a language specification, and different interpreter implementations may adopt different internal execution architectures.
1. The Overall Execution Flow of a Python Program
Taking CPython as an example, the execution process of an ordinary script can be summarized as:
flowchart TD
A["Python source code .py"] --> B["Read source code"]
B --> C["Lexical analysis and syntax analysis"]
C --> D["Generate abstract syntax tree AST"]
D --> E["Compile to bytecode"]
E --> F["Create runtime execution environment"]
F --> G["Python virtual machine executes bytecode"]
G --> H["Object operations and function calls"]
H --> I["Produce program execution results"]
I --> J["Program ends normally or exits with an exception"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This chain is the foundation for understanding Python's program execution mechanism.
II. Stage One: Source Code Reading
Python programs are usually stored in .py files.
For example:
# hello.py
message = "Hello, Python!"
print(message)
When executing:
python hello.py
The operating system starts the Python interpreter process and passes the program file to the interpreter as a runtime argument.
The interpreter reads the source code content based on the file path, and then enters the code parsing stage.
1. Source Code Files and the Interpreter
Two concepts need to be distinguished:
- Python source code: the
.pyfile written by the developer. - Python interpreter: the software responsible for parsing and executing Python programs.
The source code itself is just text; it will not execute automatically just because it is saved as a .py file.
The program must be launched through the Python interpreter or another compatible execution environment.
2. Python File Encoding
Python 3 uses UTF-8 as the source code encoding by default.
For example:
message = "你好,Python!"
print(message)
Under normal circumstances, Chinese strings can be used directly.
If the source code uses an incompatible encoding, the interpreter may produce an encoding error when reading or decoding the source file.
You can use the following code to check the default text encoding used by the current interpreter:
import sys
print(sys.getdefaultencoding())
Note that source code encoding, standard input/output encoding, and file read/write encoding are different concepts and should not be confused.
3. Current Working Directory and Script Path
When a program executes, the current working directory affects the resolution of relative paths.
For example:
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
Here, data.txt is usually looked up relative to the current working directory, not necessarily relative to the directory containing hello.py.
You can check the current working directory:
import os
print(os.getcwd())
Check the current script file path:
import os
print(os.path.abspath(__file__))
__file__ usually exists in modules loaded from a file, but it may not exist in some interactive environments.
If you need to locate a resource file based on the script's location, you can use:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
DATA_FILE = BASE_DIR / "data.txt"
print(DATA_FILE)
3. Second Stage: Lexical Analysis and Syntax Analysis
After the source code has been read, the interpreter needs to understand the structure of the code.
This process usually involves lexical analysis and syntax analysis.
1. Lexical Analysis
Lexical analysis is responsible for splitting source code into basic units with syntactic meaning; these basic units are usually called tokens.
For example:
total = price * 2
It can identify:
| Token | Type | Meaning |
|---|---|---|
total |
Identifier | Variable name |
= |
Operator | Assignment symbol |
price |
Identifier | Variable name |
* |
Operator | Multiplication operator |
2 |
Numeric literal | Integer constant |
Lexical analysis mainly addresses:
- Which characters form identifiers.
- Which characters form numbers.
- Which characters form strings.
- Which characters are operators.
- Which characters are keywords.
- How to recognize comments and whitespace characters.
You can use the Python standard library tokenize to inspect the tokens in source code:
import io
import tokenize
source = "total = price * 2"
tokens = tokenize.generate_tokens(io.StringIO(source).readline)
for token in tokens:
print(token)
In this way, you can observe how source code is split into different lexical units.
2. Syntax Analysis
After lexical analysis produces tokens, it is still necessary to determine whether these tokens conform to Python's syntax rules.
For example:
total = price * 2
This conforms to Python syntax.
Whereas:
total = * price 2
This does not conform to Python syntax.
Syntax analysis organizes tokens according to Python's syntax rules and determines the structural relationships between them.
Common syntactic structures include:
- Assignment statements.
- Function calls.
- Conditional statements.
- Loop statements.
- Function definitions.
- Class definitions.
- Expressions.
- Import statements.
If the syntactic structure is invalid, a SyntaxError is usually raised.
For example:
if True
print("Hello")
Because the if statement is missing a colon, the interpreter reports a syntax error.
The correct form is:
if True:
print("Hello")
3. The Difference Between Lexical Analysis and Syntax Analysis
| Comparison dimension | Lexical analysis | Syntax analysis |
|---|---|---|
| English name | Lexical Analysis | Syntax Analysis |
| Input | Source code characters | Token sequence |
| Core task | Identify basic lexical units | Organize syntax structure |
| Main result | Token | Syntax structure or AST |
| Typical issues | Illegal characters, invalid lexical structures | Mismatched parentheses, syntax structure errors |
It can be simply understood as follows:
- Lexical analysis determines which basic units the code consists of.
- Syntax analysis determines how these basic units form a valid program.
IV. Stage 3: Generating the Abstract Syntax Tree (AST)
After syntax analysis is complete, CPython builds an Abstract Syntax Tree (AST).
The AST is a tree structure used to represent the syntactic structure of a program.
It retains important semantic relationships in the code while omitting some details unrelated to program structure, such as certain punctuation and whitespace formatting.
1. What Is an Abstract Syntax Tree?
For example:
result = 10 + 20
From a logical structure perspective, it can be represented as:
Assignment statement
├── Target variable: result
└── Addition expression
├── Left operand: 10
└── Right operand: 20
As can be seen, the AST does not merely store source code text; it transforms the code into a structure with hierarchical relationships.
2. Using the ast Module to View the Syntax Tree
Python provides the standard library ast, which can parse Python source code and generate an AST.
For example:
import ast
source = "result = 10 + 20"
tree = ast.parse(source)
print(ast.dump(tree, indent=4))
The output is similar to:
Module(
body=[
Assign(
targets=[
Name(id='result', ctx=Store())
],
value=BinOp(
left=Constant(value=10),
op=Add(),
right=Constant(value=20)
)
)
],
type_ignores=[]
)
From the output, you can see:
Module: module node.Assign: assignment statement.Name: variable name.Constant: constant.BinOp: binary operation expression.Add: addition operation.
Together, these nodes express the structure of the program.
3. The Role of AST
The AST is an important foundation for compilers and static analysis tools.
Common uses include:
Code analysis
Analyze the structure of variables, functions, classes, and expressions.
Code transformation
Modify AST nodes and then generate new code or compilation results.
Static checking
Check for potential issues, such as unused variables, dangerous function calls, or non-compliant code structures.
Code generation
Convert the AST into bytecode or another target representation.
For example, some code formatting tools, static analysis tools, and code transformation tools use the AST or related syntax structures.
4. Differences Between AST and Source Code
| Comparison dimension | Source code | AST |
|---|---|---|
| Representation | Text | Tree structure |
| Main purpose | Writing and reading programs | Representing and analyzing program structure |
| Whether it contains formatting details | Usually yes | Usually does not retain all formatting details |
| Main users | Developers | Compilers, analysis tools |
| Whether it can be executed directly | Cannot be executed directly as machine instructions | Usually requires further compilation or processing |
The AST is not the final form in which a Python program is executed.
In CPython's typical execution flow, the AST still needs to go through the compilation stage to generate a code object.
V. Stage 4: Compiling to Bytecode
After the AST is built, CPython compiles it into Python bytecode.
Bytecode is an intermediate instruction representation for the Python virtual machine.
It is not machine code executed directly by the CPU.
1. What Is Python Bytecode?
Bytecode can be understood as a set of instructions that the Python virtual machine can recognize and execute.
For example:
a = 10
b = 20
c = a + b
print(c)
After compilation, the corresponding bytecode instructions are generated.
The instruction names, parameter formats, and execution methods may change between different Python versions.
Therefore, the bytecode instructions of a particular version should not be regarded as a permanent, unchanging language specification.
2. Using dis to Inspect Bytecode
Python provides the dis module for disassembling code objects.
For example:
import dis
def calculate():
a = 10
b = 20
c = a + b
return c
dis.dis(calculate)
The output will show the bytecode instructions corresponding to the function.
This helps you further understand:
- How variables are loaded.
- How constants are read.
- How operations are performed.
- How functions are called.
- How return values are passed.
The exact output depends on the Python version.
3. The Difference Between Bytecode and Machine Code
| Comparison Dimension | Python Bytecode | Machine Code |
|---|---|---|
| Target | Python virtual machine | A specific CPU architecture |
| Portability | Affected by the Python version and implementation | Usually affected by the CPU architecture |
| Execution method | Processed by the interpreter or a related execution engine | Executed directly by the processor |
| Instruction system | Python bytecode instructions | CPU instruction set |
| Typical use | Execution inside a Python program | Execution by the operating system and hardware |
Bytecode is not machine code, nor does it mean that the Python source code has become a standalone native executable program.
4. What Is a Code Object
An important result produced during the compilation stage is the code object (Code Object).
A code object stores the information needed to execute the code, such as:
- The bytecode.
- Constants.
- Name references.
- Local variable information.
- Parameter information.
- Information related to source code locations.
You can use the built-in function compile() to compile code manually:
source = "print('Hello, Python!')"
code = compile(source, "<string>", "exec")
print(type(code))
Output:
<class 'code'>
Then you can execute it via exec():
exec(code)
Output:
Hello, Python!
Here:
compile()is responsible for compiling source code into a code object.exec()is responsible for executing the code object.
Note that exec() can execute dynamic code. Do not use exec() directly on untrusted input, or you may introduce serious security risks.
VI. Stage Five: Bytecode Caching and .pyc Files
To reduce some of the repeated compilation work, CPython uses a bytecode caching mechanism.
The common cache file extension is .pyc.
1. What Is a .pyc File
.pyc is a compiled Python bytecode cache file.
When importing a module that meets the caching conditions, CPython typically caches the compilation result in the __pycache__ directory.
For example:
project/
├── main.py
├── utils.py
└── __pycache__/
└── utils.cpython-314.pyc
The cpython-314 in the file name indicates that the cache is tied to the corresponding CPython version.
The actual file names and directory structure depend on the interpreter implementation and version.
2. How .pyc Files Are Generated
Take importing utils.py as an example:
# utils.py
def add(a, b):
return a + b
Import it in another file:
import utils
print(utils.add(10, 20))
When loading a module, CPython decides whether to use the cache based on factors such as whether the cache exists, the cache header information, and the state of the source file.
The overall process can be represented as:
flowchart TD
A["Import Python module"] --> B{"Is there an available .pyc cache"}
B -->|"Yes"| C["Check cache validity"]
B -->|"No"| D["Read source code and compile"]
C --> E{"Is the cache valid"}
E -->|"Yes"| F["Load code object from cache"]
E -->|"No"| D
D --> G["Generate new code object"]
G --> H["Write bytecode cache conditionally"]
H --> I["Execute module code"]
F --> I
I --> J["Complete module loading"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note: what is described here is the typical cache logic during module import; not every way of executing a Python file generates a .pyc file.
3. Whether a .pyc Can Be Executed Directly
A .pyc file cannot simply be understood as a standalone executable file.
It usually requires a compatible Python implementation and version to load and interpret the code objects it contains.
Therefore:
- A
.pycis not a Windows.exe. - A
.pycis not a Linux ELF executable. - A
.pycis not equivalent to native CPU machine code. - A
.pycusually has a compatibility relationship with the Python version and implementation.
4. How to View the Cache Directory
You can use:
import sys
print(sys.implementation.cache_tag)
You can also view Python's cache directory:
import sysconfig
print(sysconfig.get_path("pycache"))
You can also use:
import importlib.util
print(importlib.util.cache_from_source("utils.py"))
These tools can help developers understand the location and naming rules of Python module caches.
VII. Stage Six: Creating the Runtime Execution Environment
After bytecode is generated, a runtime environment is also needed to support program execution.
The Python runtime is not just a virtual machine; it also includes several parts such as the object system, memory management, the exception mechanism, the module system, and built-in functionality.
1. What Is the Python Runtime
The Python runtime is a set of mechanisms and components that provide support during program execution.
It mainly includes:
| Component | Role |
|---|---|
| Python virtual machine | Executes bytecode |
| Object model | Manages Python objects and their behavior |
| Memory management | Allocates and reclaims object memory |
| Exception mechanism | Creates, propagates, and handles exceptions |
| Module system | Manages module loading and importing |
| Built-in namespace | Provides built-in functions and types |
| Execution frame | Stores the context information required for code execution |
| Garbage collection mechanism | Handles object lifecycles and circular references |
Together, these components ensure that Python programs can run normally.
2. Initialization of the Runtime Environment
When the Python interpreter starts, it needs to complete a series of initialization tasks.
For example:
- Initialize the interpreter's running state.
- Create the necessary built-in objects.
- Establish the built-in namespace.
- Initialize the module import mechanism.
- Configure system parameters.
- Set up the standard input, standard output, and standard error streams.
- Prepare the execution environment for the main module.
The exact initialization order and internal structure change as CPython versions evolve.
3. The Main Module and main
When Python runs a script directly, the script is usually executed as the main module.
For example:
print(__name__)
Run:
python hello.py
Typically outputs:
__main__
This is because Python names the current main program module __main__.
Therefore, a common code pattern is:
def main():
print("Hello, Python!")
if __name__ == "__main__":
main()
It can distinguish between:
- Running the current file directly.
- Importing the current file as a module.
When the file is executed directly, __name__ is usually "__main__", the condition is true, and main() is called.
When the file is imported by another module, __name__ is usually the module name, the condition is false, and the entry function is not executed automatically.
This is a common way of organizing a Python program entry point.
VIII. Stage Seven: Python Virtual Machine Executes Bytecode
After runtime initialization is complete, the program enters the actual execution phase.
In CPython, the Python Virtual Machine (PVM) is responsible for processing bytecode instructions.
1. What Is the Python Virtual Machine?
The Python Virtual Machine is one of the core execution mechanisms in the CPython runtime.
It is responsible for:
- Reading bytecode from code objects.
- Executing the corresponding instructions.
- Manipulating runtime objects.
- Managing execution contexts.
- Handling function calls.
- Propagating exceptions.
- Controlling the order of program execution.
It can be understood as a runtime engine capable of executing Python bytecode.
2. Bytecode Execution Example
For example:
def calculate():
a = 10
b = 20
return a + b
result = calculate()
print(result)
During execution:
- Create and bind the function object.
- Call
calculate(). - Create the context required for function execution.
- Execute variable assignment instructions.
- Perform the addition operation.
- Return the calculation result.
- Bind the result to
result. - Call
print()to output the result.
The overall execution process can be represented as:
flowchart TD
A["Execute main module code"] --> B["Create function object"]
B --> C["Call calculate()"]
C --> D["Set up function execution context"]
D --> E["Read bytecode instructions"]
E --> F["Load constants and variables"]
F --> G["Perform addition"]
G --> H["Return calculation result"]
H --> I["Bind result variable"]
I --> J["Call print()"]
J --> K["Output result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3. Execution Frame (Frame)
When a function is called, Python needs to save the context information required for the current execution.
This information includes:
- The code object currently being executed.
- Local variables.
- The global variable access context.
- The built-in namespace.
- The current execution position.
- The exception handling state.
- Other execution-related information.
These execution contexts are usually managed through mechanisms related to execution frames (Frame).
For example:
def add(a, b):
result = a + b
return result
value = add(10, 20)
When add() is called, the interpreter needs to establish a corresponding execution context for the function execution.
After the function returns, the current function execution process ends, and the related execution state is cleaned up according to runtime rules.
Note that the specific internal implementation of execution frames is a CPython implementation detail, and the internal data structures of a particular version should not be treated as part of the Python language specification.
4. Call Stack and Function Calls
When a function calls another function, a nested execution relationship is formed.
For example:
def c():
print("Function C")
def b():
c()
def a():
b()
a()
Execution order:
a()
b()
c()
return to b
return to a
Program ends
From the perspective of the call relationships:
flowchart TD
A["Call a()"] --> B["Call b()"]
B --> C["Call c()"]
C --> D["c() returns"]
D --> E["b() returns"]
E --> F["a() returns"]
F --> G["Main program continues"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Function calls usually exhibit a last-in, first-out execution relationship.
This is also an important foundation for understanding recursion, function nesting, and the call stack.
IX. Eighth Stage: Object Creation, Variable Binding, and Memory Management
Python is a dynamically typed language; during program execution, a large number of objects are created.
Understanding the object model can further help in understanding variable assignment, function calls, and memory management.
1. Python Variables Are Essentially Name Bindings
For example:
name = "Python"
This can be understood as:
- Create or obtain a string object.
- Bind the name
nameto that object.
A variable name is not the object itself, but a way to access the object.
For example:
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
Output:
[1, 2, 3, 4]
[1, 2, 3, 4]
This is because both a and b reference the same list object.
You can use is to determine whether two names point to the same object:
print(a is b)
Output:
True
2. Object Creation and Types
In Python, integers, strings, lists, functions, class instances, etc. are all objects.
For example:
number = 100
text = "Hello"
items = [1, 2, 3]
print(type(number))
print(type(text))
print(type(items))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
Variables do not need to be declared with a fixed type in advance; a name can be bound to objects of different types at different times:
value = 100
print(type(value))
value = "Python"
print(type(value))
This reflects the dynamic typing feature of Python.
3. Python Memory Management
The Python runtime is responsible for managing the memory lifecycle of objects.
Taking CPython as an example, this mainly involves:
- Reference counting.
- Cyclic garbage collection.
- Memory allocator.
- Object memory management.
Reference counting is used to track how objects are referenced.
When an object is no longer referenced, its memory can usually be reclaimed.
However, cyclic references can cause simple reference counting to be unable to reclaim objects, so CPython also provides a cyclic garbage collection mechanism.
For example:
import gc
print(gc.get_count())
print(gc.isenabled())
This can be used to view part of the current state of the garbage collector.
Note:
- Reference counting is an important implementation mechanism in CPython.
- Different Python implementations may use different memory management strategies.
- After an object is released, the underlying memory is not necessarily returned to the operating system immediately.
- You should not rely on an object being destroyed at a particular moment.
10. Ninth Stage: Module Import and Dependency Loading
Python programs usually do not put all code in a single file; instead, they organize code through modules and packages.
When import is executed, Python starts the module lookup and loading mechanism.
1. The Basic Process of Module Import
For example:
import math
print(math.sqrt(16))
The interpreter needs to:
- Check whether the module has already been loaded.
- Locate the module according to the module lookup rules.
- Load the module code.
- Execute the module initialization code.
- Bind the module object to the current namespace.
Module lookup usually involves:
- Built-in modules.
- Modules in the current import system's module cache.
- Modules in the file system.
- Installed third-party packages.
- Custom importers.
2. The sys.modules Module Cache
Python uses sys.modules to store module objects that have already been loaded.
For example:
import sys
import math
print("math" in sys.modules)
It usually outputs:
True
When importing a module that has already been loaded again, Python usually can directly reuse the module cache without having to fully reload the module.
3. The sys.path Module Search Path
You can view the module search path with the following code:
import sys
for path in sys.path:
print(path)
sys.path is one of the important search paths used by the module lookup mechanism.
If a third-party module cannot be imported, you can check:
- Whether the module is installed.
- Whether the current interpreter is correct.
- Whether the module is in the search path.
- Whether a file with the same name is causing a conflict.
- Whether the virtual environment is activated.
4. The Relationship Between Module Import and Program Execution
Module import is not just about finding a file; it may also execute the module's top-level code.
For example:
# utils.py
print("utils module loaded")
def add(a, b):
return a + b
Another file:
import utils
print(utils.add(10, 20))
Running result:
utils module loaded
30
The module's top-level code usually executes when the module is first loaded.
Therefore, you should avoid performing unnecessary side-effect operations such as network requests and file overwrites during the module import stage.