系统相关
首页 > 系统相关> > Python脚本不删除Windows中的Git文件

Python脚本不删除Windows中的Git文件

作者:互联网

我正在使用以下代码删除包含git repo的目录:

import errno
import os
import stat
import shutil


def clear_dir(path):
    shutil.rmtree(path, ignore_errors=False, one rror=handle_remove_readonly)


def handle_remove_readonly(func, path, exc):
  excvalue = exc[1]
  if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
      os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
      func(path)
  else:
      raise

此代码应处理只读文件.我可以从Windows资源管理器中删除目录/文件夹,但是当我运行以下代码时:

if __name__ == '__main__':
    clear_dir(r'c:\path\to\ci-monitor')

我收到以下错误:

  File "C:\Users\m45914\code\ci-monitor\utils\filehandling.py", line 8, in clear_dir                              
    shutil.rmtree(path, ignore_errors=False, one rror=handle_remove_readonly)                                      
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 488, in rmtree                
    return _rmtree_unsafe(path, one rror)                                                                          
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe        
    _rmtree_unsafe(fullname, one rror)                                                                             
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe        
    _rmtree_unsafe(fullname, one rror)                                                                             
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe        
    _rmtree_unsafe(fullname, one rror)                                                                             
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe        
    _rmtree_unsafe(fullname, one rror)                                                                             
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 383, in _rmtree_unsafe        
    one rror(os.unlink, fullname, sys.exc_info())                                                                  
  File "C:\Users\m45914\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 381, in _rmtree_unsafe        
    os.unlink(fullname)                                                                                           
PermissionError: [WinError 5] Access is denied: 'scratch\\repos\\ci-monitor\\.git\\objects\\pack\\pack-83e55c6964d
21e8be0afb2cbccd887eae3e32bf4.idx'                                                                                

我尝试以管理员身份运行脚本(没有更改.)

被删除的目录是git repo,我定期克隆,检查和删除它.检查是为了确保repo中没有未合并的版本和修补程序分支.

有人有任何想法吗?

解决方法:

如果该文件正由另一个进程使用,则无法将其删除.通过使用’unlocker’或任何其他类似软件进行交叉检查.

标签:python,git,delete-file,windows
来源: https://codeday.me/bug/20190706/1393918.html