Python Code Execution

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 :

  1. 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.
  2. 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.
  3. The AST is then processed into Python Byte code – which is a high level stack based set of Opcodes for a Python Virtual Machine.
  4. 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
  5. 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.
  6. 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.

Author: Aditya Bhuyan

I am an IT Professional with close to two decades of experience. I mostly work in open source application development and cloud technologies. I have expertise in Java, Spring and Cloud Foundry.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s