Changing the directory where .pyc files are created

20,430

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
20,430
Scharron
Author by

Scharron

Big Data Sergeant at Data Publica

Updated on July 09, 2022

Comments

  • Scharron
    Scharron almost 2 years

    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 ?

    • yantrab
      yantrab over 13 years
      Can you tell us more about why you want to move them?
    • Scharron
      Scharron over 13 years
      It was just out of curiosity, to keep directories clean.
    • mattgately
      mattgately over 6 years
      I was wondering the same thing. I have a case where the directories with the source files are not writable, and want to relocate the pycache so that all users can benefit from the cache without having write access to the actual python source file directories.
  • Aniket Thakur
    Aniket Thakur over 8 years
    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__.
  • bers
    bers over 3 years
    This answer is outdated, check stackoverflow.com/a/60024195/880783
  • xcodz-dot
    xcodz-dot almost 3 years
    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.