如何删除 git 存储库,在 python,在 windows

How to remove git repository, in python, on windows

如标题所述,我需要使用 python 删除 git 存储库。 我已经看到关于这个相同主题的其他问题,但 none 的解决方案似乎对我有用。

我的作品: 我需要使用 gitpython 下载一个存储库,然后检查一些不相关的东西。该过程完成后,我需要删除存储库以便为使用我的脚本的任何人保存 space。

问题: 克隆 git 存储库时,将创建一个 .git 文件。此文件隐藏在 windows 中,我一直在使用的模块无权删除 .git 文件夹中的任何文件。

我试过的:

import shutil
shutil.rmtree('./cloned_repo')

PermissionError: [WinError 5] Access is denied:

如能提供有关此问题的任何帮助,我们将不胜感激。

Git 有一些只读文件。您需要先更改权限:

import subprocess
import shutil
import os
import stat
from os import path
for root, dirs, files in os.walk("./cloned_repo"):  
    for dir in dirs:
        os.chmod(path.join(root, dir), stat.S_IRWXU)
    for file in files:
        os.chmod(path.join(root, file), stat.S_IRWXU)
shutil.rmtree('./cloned_repo')

如上所述,这是因为 Git 的许多文件是只读的,Python 在 Windows 上无法正常删除。 GitPython 模块有一个实用函数就是为了这个目的:git.util.rmtree

像这样调用函数应该可以解决您的问题:

from git import rmtree
rmtree('./cloned_repo')

您还可以看到 their source here——它与上面的答案类似,截至 2020 年 12 月。