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

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

  • автор:

Удаление из Git-репозитория файла или папки

Каким образом можно удалить файл/папку из опубликованного репозитория, в частности из github ? Все статьи на эту тему мне попались с удалением из локального репозитория, и ни одной, как удалить из опубликованного.

Отслеживать
задан 25 июн 2021 в 5:18
141 10 10 бронзовых знаков
Удаляем, создаём коммит, пушим.
25 июн 2021 в 5:26
Если надо удалить из истории, то ru.stackoverflow.com/…
25 июн 2021 в 5:26

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

  1. Удалить локально
  2. Выполнить git push —force

Отслеживать
ответ дан 25 июн 2021 в 5:24
Герман Борисов Герман Борисов
10.6k 14 14 серебряных знаков 38 38 бронзовых знаков
вот только зачем рекомендовать force?
25 июн 2021 в 6:11
@KoVadim, а вы знаете другой способ изменения опубликованной истории?
28 июн 2021 в 4:37
если нам просто нужно удалить файл (а не почистить всю историю от него), то force не нужен.
28 июн 2021 в 8:48
@KoVadim, мне даже в голову не пришло, что вопрос может быть в этом. Спасибо за уточнение
28 июн 2021 в 13:09

  • git
  • github
  • git-репозиторий
    Важное на Мете
Похожие

Подписаться на ленту

Лента вопроса

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.4.30.8412

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.

Git

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.

# .gitignore  # Pyhon byte-compiled / optimized files __pycache__/ *.py[cod] *$py.class 

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

// settings.json  "files.exclude":   "**/__pycache__": true > 

Neovim

-- init.vim or init.lua or nvimtree.lua  local nt = lvim.builtin.nvimtree  -- Ingore/Exclude directories/files patterns nt.setup.filters.custom =   "__pycache__", > 

Vim

" .vimrc or nerdtree.vim  " NERDTree Plugin"  " Ingore/Exclude directories/files patterns  let NERDTreeIgnore = [  \ '\.pyc$',  \ '^__pycache__$',  \] 

Docker

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

# Dockerfile   ENV PYTHONDONTWRITEBYTECODE 1 

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:

$ find . | grep -E "(/__pycache__$|\.pyc$|\.pyo$)" | xargs rm -rf 

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

$ find . | grep -E "(/__pycache__$|\.pyc$|\.pyo$)" 

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

alias rm-pycache='find . | grep -E "(/__pycache__$|\.pyc$|\.pyo$)" | xargs rm -rf' 

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

rm-pycache:  find . | grep -E "(/__pycache__$|\.pyc$|\.pyo$)" | xargs rm -rf 

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:

$ export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/" 

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

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.

At last they are out of my sight.

Удаление файлов в репозитории

Вы можете удалить отдельный файл или весь каталог в репозитории на GitHub.

Кто эту функцию можно использовать?

People with write permissions can delete files or directories in a repository.

В этой статье

About file and directory deletion

You can delete an individual file in your repository or an entire directory, including all the files in the directory.

If you try to delete a file or directory in a repository that you don’t have write permissions to, we’ll fork the project to your personal account and help you send a pull request to the original repository after you commit your change. For more information, see «About pull requests.»

If the file or directory you deleted contains sensitive data, the data will still be available in the repository’s Git history. To completely remove the file from GitHub, you must remove the file from your repository’s history. For more information, see «Removing sensitive data from a repository.»

Deleting a file

  1. Browse to the file in your repository that you want to delete.
  2. In the top-right corner, select the

dropdown menu, then click Delete file.

Screenshot of the file list for a directory. To the right of the directory name, a button, labeled with a kebab icon, is outlined in dark orange.

Screenshot of a GitHub pull request showing a dropdown menu with options to choose the commit author email address. octocat@github.com is selected.

Screenshot of a GitHub pull request showing a radio button to commit directly to the main branch or to create a new branch. New branch is selected.

Deleting a directory

  1. Browse to the directory in your repository that you want to delete.
  2. In the top-right corner, select the

dropdown menu, then click Delete directory.

Removing __pycache__ from git repository

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:

  • Remove a file from a Git repository without deleting it from the local filesystem
  • Applying .gitignore to committed files
  • How can I make Git «forget» about a file that was tracked, but is now in .gitignore?
  • Remove sensitive files and their commits from Git history

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

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