What user do python scripts run as in windows?

DevelopingChris picture DevelopingChris · Jul 31, 2009 · Viewed 29.8k times · Source

I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?

WindowsError: [Error 5] Access is denied: 'path'

is what I get when I run the script.
I've tried

shutil.rmtree  
os.remove  
os.rmdir

they all return the same error.

Answer

ThomasH picture ThomasH · Jul 31, 2009

We've had issues removing files and directories on Windows, even if we had just copied them, if they were set to 'readonly'. shutil.rmtree() offers you sort of exception handlers to handle this situation. You call it and provide an exception handler like this:

import errno, os, stat, shutil

def handleRemoveReadonly(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

shutil.rmtree(filename, ignore_errors=False, onerror=handleRemoveReadonly)

You might want to try that.