1. Process overview
Python first compiles the code (. py file) into bytecode, gives it to the bytecode virtual machine, and then executes the bytecode instruction by executing a byte-code command on the virtual machine to complete the execution of the program.
2. Byte code
The byte code corresponds to the Pycodeobject object in the Python virtual machine program.
The. PYc file is a representation of the bytecode on disk.
3. pyc file
The time when the Pycodeobject object is created is when the module is loaded, that is, import.
Python test.py compiles the test.py into bytecode and interprets execution, but does not generate TEST.PYC.
If test.py loads other modules, such as import Util,python compiles the util.py into bytecode, generates UTIL.PYC, and executes the bytecode interpretation.
If you want to generate TEST.PYC, we can use the Python built-in module Py_compile/compileall to compile.
When the module is loaded, if both. py and. Pyc,python try to use. PYC, if the. PYc is compiled earlier than the. Py modification time, recompile the. py and update. PYc.
4. Pycodeobject
The result of the Python code compilation is the Pycodeobject object.
typedef struct {
Pyobject_head
int co_argcount; /* Number of positional parameters */
int co_nlocals; /* Number of local variables */
int co_stacksize; /* Stack size */
int co_flags;
Pyobject *co_code; /* Byte code instruction sequence */
Pyobject *co_consts; /* All constant sets */
Pyobject *co_names; /* All symbol name sets */
Pyobject *co_varnames; /* Local variable name collection */
Pyobject *co_freevars; /* Variable name set for the closure of the packet */
Pyobject *co_cellvars; /* variable name set referenced by inner nested function */
/* The rest doesn ' t count for hash/cmp */
Pyobject *co_filename; /* The name of the code */
Pyobject *co_name; /* Module name | function name | class name */
int Co_firstlineno; /* The starting line number of the code block in the file */
Pyobject *co_lnotab; /* Byte code instruction and line number corresponding relation */
void *co_zombieframe; /* for optimization only (see FRAMEOBJECT.C) */
} Pycodeobject;