Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the directory where .pyc files are created

Is there a way to change the directory where .pyc file are created by the Python interpreter? I saw two PEPs about that subject (0304 and 3147), but none seems to be implemented in the default interpreter (I'm working with Python 3).

Did I miss something ?

like image 676
Scharron Avatar asked Aug 19 '10 13:08

Scharron


People also ask

Where is .PYC file located?

pyc files are placed in the same directory as the . py file. In Python 3.2, the compiled files are placed in a __pycache__ subdirectory, and are named differently depending on which Python interpreter created them. (This can be useful to people importing the same Python modules from multiple versions of Python.)

When .PYC file is created?

When a Python source file (module) is imported during an execution for the first time, the appropriate . pyc file is created automatically. If the same module is imported again, then the already created . pyc file is used.

Can I delete __ Pycache __ folder?

Explains: First finds all __pycache__ folders in current directory. Execute rm -r {} + to delete each folder at step above ( {} signify for placeholder and + to end the command)

What is __ Pycache __? What are .PYC files?

__pycache__ is a directory that contains bytecode cache files that are automatically generated by python, namely compiled python, or . pyc , files.


2 Answers

Yes, starting from Python 3.8 you can control this behavior. The original discussion starts from pep 304 in 2003.

While this original PEP was withdrawn, a variant of this feature was eventually implemented for Python 3.8 in https://bugs.python.org/issue33499

In the result, you can control using PYTHONPYCACHEPREFIX=path, -X pycache_prefix=path and sys.pycache_prefix.

like image 64
funnydman Avatar answered Oct 18 '22 19:10

funnydman


This might be useful for some: Miscellaneous options, especially -B option:

If given, Python won’t try to write .pyc files on the import of source modules. See also PYTHONDONTWRITEBYTECODE.

like image 29
Hans Avatar answered Oct 18 '22 18:10

Hans