5

Simple test case with python 2.7 on windows 7 prof 64 bits: via python I checkout a git project in a directory, let's say, c:/temp/project. Afterwards I delete it with the python command

shutil.rmtree('c:/temp/project')

After the command, the folder is empty (no hidden files) but it cannot be removed it self because of the following error:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:\\temp\\project'

I've checked and git is not running at that moment (I've even tried a sleep(10) to be sure). I've tried this solution:

What user do python scripts run as in windows?

but it doesn't work, same error. Tried a os.system('rmdir') but same error. Tried win32api.SetFileAttributes() function but same error. If I delete the folder via explorer, there's no problem.

How can I solve the problem?

Community
  • 1
  • 1
marco
  • 1,686
  • 1
  • 25
  • 33

3 Answers3

3

The OP was running in the wrong dir ... but i found this thread for a problem using GitPython; seems like a common case, as git-python will hold handles to your repo if you don't clean up in some odd ways:

import gc, stat

gc.collect()
your_repo_obj.git.clear_cache()

# now this will succeed: 
shutil.rmtree(your_repo_dir)

the need for these gymnastics are due to both a bug, and by design. This bug describes the reasons: https://github.com/gitpython-developers/GitPython/issues/553

some bits flipped
  • 2,592
  • 4
  • 27
  • 42
0

You are probably executing the Python code inside the folder you are trying to remove.

geertjanvdk
  • 3,440
  • 24
  • 26
0

I have the same problem. My solution:

import stat, os, shutil
from pathlib import Path

def readonly_to_writable(foo, file, err):
  if Path(file).suffix in ['.idx', '.pack'] and 'PermissionError' == err[0].__name__:
    os.chmod(file, stat.S_IWRITE)
    foo(file)

shutil.rmtree('repo-catalog/', onerror=readonly_to_writable)
  • Hello, please don't just submit code in your answer(s), add some details as to why you think this is the optimal solution. – Destroy666 May 31 '23 at 12:45
  • @Destroy666 Oops. I was looking for a solution to the same problem, but did not follow the link in the topic. I would have solved my problem faster if I followed this link. [This solution](https://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows/1214935#1214935) is better for my case (I didn't use a GitPython). – Maksim Sych May 31 '23 at 14:40