In Python execution environment you would find two different actors.
- Python script – a text file containing code in the Python programming language – normally a
.py
file - Python interpreter – The python executable (On Unix this is located at /usr/bin/python for instance). On CPython (the normal distributed version) this application is written in C.
I will describe how CPython works – this is the reference version available from python.org.
When Python is asked to execute a python script this happens by the Python Interpreter being executed and being passed a Python Script as an argument.
The steps are as follows :
- The update time of the script is compared with the update time of a
.pyc
file of the same name in the appropriate directory (for python3 this is in the__pycache__
directory). If the.pyc
file exists and is more recent than the.py
file , go directly to step 5. - The .py file is then parsed into a AST (Abstract Syntax Tree) – which describes in an internal format how how each element Python script relates to each other element (which expression is part of which function/method for instance. Syntax Errors are raised at this stage as needed.
- The AST is then processed into Python Byte code – which is a high level stack based set of Opcodes for a Python Virtual Machine.
- Assuming that the Default options are in place – the Python Byte code is written to the Byte code cache directory (
__pycache__
directory) as .pyc files - The Byte code is pass to a Virtual machine within the Python Executable – Essentially the Virtual machine is a large loop which takes the OP codes one at at time and executes them. Most of those Op Codes result in a result being place on the internal stack, for the next OP code to operate on. Run-time Errors are raised at this stage when encountered.
- When the program encounters the end of the set of Op codes, it will exit the Python Virtual Machine; and thereby exit the Python Executable.