Как удалить pycache из репозитория
Перейти к содержимому

Как удалить pycache из репозитория

  • автор:

Delete Python’s __pycache__ directories

First things first, actually I don’t want to remove them at all, I just want to get rid of them forever from my workflow. We will see that later.

This is a compherensive guide to deal with Python’s __pycache__ directories and .pyc files.

__pycache__ is a directory which is containing Python 3 bytecode compiled and ready to be executed.

From the official python tutorial Modules:

To speed up loading modules, Python caches the compiled version of each module in the pycache directory under the name module.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.6 the compiled version of spam.py would be cached as pycache/spam.cpython-36.pyc.

When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a .pyc file containing the compiled code should be created in a pycache subdirectory of the directory containing the .py file. The .pyc file will have a filename that starts with the same name as the .py file, and ends with .pyc, with a middle component that depends on the particular python binary that created it.

So they are necessary and should not be deleted usually.

Solution — Default

There are a lot elements to “remove” __pycache__ directories and .pyc files.

The first and foremost thing is that we need to do ignoring them in our project’s git trees. Add them into our .gitignore file(s), locally and/or globally.

Editor

However this is not enough, even though we already added them into .gitignore file(s), we will still see them in our IDEs and explorers. In order to prevent that I use below configurations per editor.

VSCode

Neovim

Vim

Docker

There is a environment variable which is responsible to disable to write .pyc files named PYTHONDONTWRITEBYTECODE .

PYTHONDONTWRITEBYTECODE

If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.

It’s not usually an optimum solution to set this variable in other than containers. Since you run a single python process in containers, which does not spawn other python processes during its lifetime, then there is no disadvantages in doing that.

Delete

After all of the above, we may still encounter some cases to delete all of __pycache__ directories. Here is the shell command to remove them:

In the root of your project run:

Before running above delete command test it running without xargs rm -rf -the remove part. This will simply list them:

You can add this command as an alias for easy access:

Also you would like to add it as a make targets in your project’s Makefile for ci/cd pipelines.

Lastly there is a python library just for this delete cause: pyclean. In my opinion it’s an overkill but you may take a look.

Solution — New

This is my current solution about the issue.

Beginning from Python 3.8 you can use PYTHONPYCACHEPREFIX environment variable to use a global cache directory to avoid them created under your projects:

By this environment variable Python won’t create any __pycache__ directory in your projects, instead it will put all of them under

PYTHONPYCACHEPREFIX

If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in pycache directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.

New in version 3.8.

You can add this environment variable in one of the configuration file of yours: .zshrc , .zshenv , .bashrc , .bash_profile , .profile , .zprofile etc.

Как удалить pycache из репозитория

How can I remove all __pycache__ subdirectories in my repository using .gitignore ?

2 Answers 2

You cannot remove files from existing commits: those commits are frozen for all time. You can make sure you do not add new files to future commits, though. Simply remove the files now, with git rm -r —cached __pycache__ , and list __pycache__ or __pycache__/ in your .gitignore (creating this .gitignore file if needed). Do this for each __pycache__ directory; use your OS’s facilities to find these (e.g., find . -name __pycache__ -type d ). Then git add .gitignore and git commit to commit the removal.

Note that any time anyone moves from any commit that has the files—where they’ll be checked out—to a commit that lacks the files, they will have their entire __pycache__ directory removed if Git is able to do that; at the least, any cached files that were committed and can be removed will be removed. So the —cached in the git rm -r —cached above only speeds things up for you by avoiding the removal of the cached compiled files this time. Others will have to rebuild their cache.

To make a new and different repository in which the __pycache__ files were ever accidentally committed in the first place, use git filter-branch (which is now deprecated) or the newfangled git filter-repo (which is not yet distributed with Git). Or, see any of these various existing questions and their answers, which you should already have found before you asked this:

Removing __pycache__ from git repository

How can I remove all __pycache__ subdirectories in my repository using .gitignore ?

2 Answers 2

You cannot remove files from existing commits: those commits are frozen for all time. You can make sure you do not add new files to future commits, though. Simply remove the files now, with git rm -r —cached __pycache__ , and list __pycache__ or __pycache__/ in your .gitignore (creating this .gitignore file if needed). Do this for each __pycache__ directory; use your OS’s facilities to find these (e.g., find . -name __pycache__ -type d ). Then git add .gitignore and git commit to commit the removal.

Note that any time anyone moves from any commit that has the files—where they’ll be checked out—to a commit that lacks the files, they will have their entire __pycache__ directory removed if Git is able to do that; at the least, any cached files that were committed and can be removed will be removed. So the —cached in the git rm -r —cached above only speeds things up for you by avoiding the removal of the cached compiled files this time. Others will have to rebuild their cache.

To make a new and different repository in which the __pycache__ files were ever accidentally committed in the first place, use git filter-branch (which is now deprecated) or the newfangled git filter-repo (which is not yet distributed with Git). Or, see any of these various existing questions and their answers, which you should already have found before you asked this:

Что такое __pycache__ в Python? Как запретить создание __pycache__ и .pyc файлов?

Что такое __pycache__ в Python? Как запретить создание __pycache__ и .pyc файлов?

В этой статье будет разобрана природа возникновения папки __pycache__, которая создается при запуске кода Python.

Введение

Наверное, вы заметили, что при выполнении кода Python __pycache__ (иногда) создается каталог с именем, который содержит множество файлов с .pyc расширением.

В этой статье мы обсудим назначение этих файлов, которые создаются интерпретатором Python. Мы обсудим, почему эти файлы генерируются, как подавить их создание и как гарантировать, что они не будут переданы в какой-либо удаленный репозиторий.

Файлы .pyc и папка __pycache__

Python является интерпретируемым языком, что означает, что ваш исходный код преобразуется в набор инструкций, понятных ЦП во время выполнения. При запуске вашей программы Python исходный код компилируется в байт-код, который является деталью реализации CPython (исходной реализации Python). Байт-код также кэшируется и сохраняется в .pyc файлах , поэтому при следующем повторном запуске кода выполнение того же файла будет быстрее.

Обратите внимание, что пара концепций, обсуждаемых в этом разделе, касающихся интерпретатора и байт-кода, упрощены и верны лишь частично, но их более чем достаточно, чтобы помочь вам понять pyc файлы и __pycache__ директории.

Таким образом, после первого выполнения вашего исходного кода будет создана папка __pycache__, содержащая несколько .pyc файлов байт-кода с теми же именами, что и ваши .py файлы. Как уже упоминалось, они будут использоваться в последующих исполнениях, чтобы ваша программа запускалась немного быстрее.

Каждый раз, когда ваш исходный код модифицируется, он будет перекомпилирован, и новые файлы байт-кода будут создаваться снова. Обратите внимание, что в некоторых случаях это может быть не так, и Python выполнит код, используя кэшированные файлы, что вызовет у вас некоторые проблемы. Например, вы, возможно, исправили ошибку, но Python может работать в кешированной версии с ошибками. В этом случае вам, возможно, придется удалить __pycache__ папку или даже запретить создание этих файлов.

Подавление/запрет создания __pycache__

При использовании интерпретатора CPython (который в любом случае является исходной реализацией Python) вы можете подавить создание этой папки двумя способами.

Первый вариант — передать -B флаг при запуске файла Python. Когда флаг указан, Python не будет пытаться записывать .pyc файлы при импорте исходных модулей:

В качестве альтернативы вы можете установить переменную среды PYTHONDONTWRITEBYTECODE в любую непустую строку. Опять же, это предотвратит попытки Python записывать .pyc файлы.

Обратите внимание, что оба подхода эквивалентны.

Добавление __pycache__ в файл .gitignore

При работе в локальном репозитории Git будет отслеживать каждый файл в репозитории Git. Каждый файл может быть отслежен (т.е. уже подготовлен и зафиксирован), не отслежен (не подготовлен или зафиксирован) или проигнорирован.

В большинстве случаев вам следует игнорировать определенные файлы, такие как файлы с конфиденциальными данными, системные файлы или автоматически сгенерированные файлы, созданные, скажем, в среде IDE или в определенной рабочей области.

Самый элегантный способ сделать это — через .gitignore файл, который находится в верхнем каталоге удаленного репозитория Git, в котором вы можете явно указать файлы или каталоги (также можно применять регулярные выражения), которые Git будет игнорировать и не будет отслеживать дольше.

__pycache__ входит в число каталогов, которые не следует помещать в удаленные репозитории. Поэтому все, что вам нужно сделать, это указать каталог в .gitignore файле.

Важное

Одно важное предостережение относительно байт-кода заключается в том, что .pyc файлы будут использоваться в тех случаях, когда эквивалентного .py файла больше нет. Например, если вы удалили или переименовали .py файл, но по какой-то причине вы все еще видите, как они выполняются любым возможным способом, то это может быть фактической причиной.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *