shutdown.rmtree 在 Windows 上失败并显示“访问被拒绝”[重复]

2024-02-19

在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'

查看文件属性对话框我注意到af.msg文件被设置为只读。

所以问题是:什么是simplest解决方法/修复来解决这个问题 - 鉴于我的意图是做相当于rm -rf build/但在 Windows 上呢? (无需使用 unxutils 或 cygwin 等第三方工具 - 因为此代码的目标是在安装了 Python 2.6 w/ PyWin32 的裸 Windows 安装上运行)


检查一下这个问题:python脚本在windows中运行时是什么用户? https://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows

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

Here's onerror()处理程序来自pathutils.py http://www.voidspace.org.uk/downloads/pathutils.py@Sridhar Ratnakumar 在评论中提到:

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
    # Is the error an access error?
    if not os.access(path, os.W_OK):
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

shutdown.rmtree 在 Windows 上失败并显示“访问被拒绝”[重复] 的相关文章

随机推荐