"访问被拒绝",Windows上的shutil.rmtree失败

Rei*_*ica 62 python windows file-permissions shutil

在Python中,当shutil.rmtree在包含只读文件的文件夹上运行时,将打印以下异常:

 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 216, in rmtree
   rmtree(fullname, ignore_errors, onerror)
 File "C:\Python26\lib\shutil.py", line 221, in rmtree
   onerror(os.remove, fullname, sys.exc_info())
 File "C:\Python26\lib\shutil.py", line 219, in rmtree
   os.remove(fullname)
WindowsError: [Error 5] Access is denied: 'build\\tcl\\tcl8.5\\msgs\\af.msg'
Run Code Online (Sandbox Code Playgroud)

在File Properties对话框中,我注意到该af.msg文件被设置为只读.

所以问题是:解决这个问题的最简单的解决方法/解决办法是什么- 考虑到我的意图是rm -rf build/在Windows上做同样的事情?(无需使用像unxutils或cygwin这样的第三方工具 - 因为此代码的目标是在安装了Python 2.6 w/PyWin32的裸Windows安装上运行)

Jus*_*eel 79

检查这个问题:

用户做什么python脚本在Windows中运行?

显然答案是将文件/文件夹更改为不是只读,然后将其删除.

这是@Sridhar Ratnakumar在评论中提到的onerror()处理程序pathutils.py:

def onerror(func, path, exc_info):
    """
    Error handler for ``shutil.rmtree``.

    If the error is due to an access error (read only file)
    it attempts to add write permission and then retries.

    If the error is for another reason it re-raises the error.

    Usage : ``shutil.rmtree(path, onerror=onerror)``
    """
    import stat
    if not os.access(path, os.W_OK):
        # Is the error an access error ?
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise
Run Code Online (Sandbox Code Playgroud)

  • 解决方案的“其他引发”部分不会引发异常。来自 Python 文档:“不会捕获由 onerror 引发的异常。” https://docs.python.org/2/library/shutil.html#shutil.rmtree (3认同)
  • 即使此答案的评论指出“将文件/文件夹更改为非只读”,我仍然收到只读文件夹的拒绝访问。[This](http://stackoverflow.com/a/1889686/116047) 实现虽然有效。 (2认同)
  • 警告那些按原样复制粘贴此函数的人,请将“import stat”移出该函数。当我将导入留在函数中并且函数位于类的 `__del__` 方法中时,我收到了 `RuntimeError: sys.meta_path must be a list of import hooks`。 (2认同)

Epc*_*lon 24

我说用os.walk实现你自己的rmtree,在尝试删除它之前,通过在每个文件上使用os.chmod来确保访问.

像这样(未经测试):

import os
import stat

def rmtree(top):
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            filename = os.path.join(root, name)
            os.chmod(filename, stat.S_IWUSR)
            os.remove(filename)
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    os.rmdir(top)      
Run Code Online (Sandbox Code Playgroud)


Ale*_*Ost 16

好吧,标记的解决方案对我不起作用......这样做了:

os.system('rmdir /S /Q "{}"'.format(directory))
Run Code Online (Sandbox Code Playgroud)