Home > Backend Development > Python Tutorial > The execution principle of Python program

The execution principle of Python program

巴扎黑
Release: 2016-12-08 10:34:24
Original
1881 people have browsed it

1. Process Overview

 Python first compiles the code (.py file) into bytecode and hands it to the bytecode virtual machine. Then the virtual machine executes the bytecode instructions one by one to complete the execution of the program.

2. Bytecode

 Bytecode corresponds to the PyCodeObject object in the Python virtual machine program.

 .pyc file is the representation of bytecode on disk.

3. pyc file

 The PyCodeObject object is created when the module is loaded, that is, import.

 Python test.py will compile test.py into bytecode and interpret it for execution, but it will not generate test.pyc.

  If test.py loads other modules, such as import util, Python will compile util.py into bytecode, generate util.pyc, and then interpret and execute the bytecode.

 If we want to generate test.pyc, we can use the Python built-in module py_compile/compileall to compile it.

When loading a module, if both .py and .pyc exist, Python will try to use .pyc. If the compilation time of .pyc is earlier than the modification time of .py, .py will be recompiled and .pyc will be updated.

4. PyCodeObject

 The compiled result of Python code 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; /* Bytecode instruction sequence*/

 PyObject *co_consts; /* All constant set*/

 PyObject *co_names; /* All symbol name set*/

 PyObject *co_varnames; /* Set of local variable names */

  PyObject *co_freevars; /* Set of variable names used for closures */

  PyObject *co_cellvars; /* Set of variable names referenced by internal nested functions */

  /* The rest doesn 't count for hash/cmp */

 PyObject *co_filename; /* File name where the code is located*/

 PyObject *co_name; /* Module name|Function name|Class name*/

 int co_firstlineno; /* Code block The starting line number in the file */

  PyObject *co_lnotab; /* Correspondence between bytecode instructions and line numbers */

  void *co_zombieframe; /* for optimization only (see frameobject.c) */

 } PyCodeObject;


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template