53

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 ?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
Scharron
  • 17,233
  • 6
  • 44
  • 63

4 Answers4

46

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.

funnydman
  • 9,083
  • 4
  • 40
  • 55
  • 9
    for linux users who do not care what happens with the pycache, this will work very well when added to .bashrc: `export PYTHONPYCACHEPREFIX=/tmp`. The cache files will be sent `/tmp` and will be cleared after 10 days or on system reboot. – AmaanK Jul 30 '21 at 14:06
  • `/tmp` works for macos too! Even better, `export PYTHONPYCACHEPREFIX=/tmp/pycache` will put all the files under pycache, creating it if needed. The advantage is that you can delete the cache easily - I've had problems deleting/renaming .py files but a forgotten import under the old name "finding" the .pyc somewhere. – JL Peyret May 11 '23 at 20:19
25

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.

funnydman
  • 9,083
  • 4
  • 40
  • 55
Hans
  • 349
  • 3
  • 6
19

There's no way to change where the .pyc files go. Python 3.2 implements the __pycache__ scheme whereby all the .pyc files go into a directory named __pycache__. Python 3.2 alpha 1 is available now if you really need to keep your directories clean.

Until 3.2 is released, configure as many tools as you can to ignore the .pyc files.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Your custom .py files get compiled and stored in .pyc file under `__pycache__` folder in same directory. You will find common compiled files under `C:\Python34\Lib\__pycache__`. – Aniket Thakur Oct 02 '15 at 12:15
  • 5
    This answer is outdated, check https://stackoverflow.com/a/60024195/880783 – bers Nov 03 '20 at 13:14
0

Python files are NOT always stored in the same directory and will get directed to pycache if you use pycache. Any answers on being able to have custom locations and names, because importing the module is rather temperamental and doesn't always work. You will be able see what I mean at github.com/LolexInc/Lolex-Tools/tree/Beta and view JTToolsInstaller.py. There is a lot of mess in it.