(Python) How to Avoid .pyc Files




Python logo

If you program in Python, you have certainly noticed that Python creates a folder named __pycache__ at several places. This folder is used by Python to store .pyc files which are Python bytecode files. They are created by the Python interpreter and can be used directly by Python’s virtual machine.

Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc and .pyo files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases.
source.

If, for any reason, the generation of the bytecode cache bother you, here are some ways to avoid .pyc files:

 

1 – In C/C++

In C/C++, just use the following Python global variable somwhere before calling Py_Initialize():

Py_DontWriteBytecodeFlag = 1;
...
Py_Initialize();

 

2 – In Python

You can prevent the creation of the bytecode cache by using the following code in your initialization section of your Python script:

import sys
sys.dont_write_bytecode = True

 
Both techniques work in Python 2 and Python 3.

By default, GeeXLab allows the generation of .pyc files. So the solution to avoid them is to use sys.dont_write_bytecode=1 in the first lines of the first INIT script.





Leave a Comment

Your email address will not be published. Required fields are marked *