在Windows上,shutil.rmtree失败,显示“访问被拒绝”
在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
文件被设置为只读。
所以问题是:解决这个问题的 最简单的 解决方法/解决方案是什么-鉴于我的意图是rm -rf
build/在Windows上做等效的事情?(无需使用诸如unxutils或cygwin之类的第三方工具-因为此代码的目标是在安装了Python2.6和PyWin32的裸机上运行)
回答:
检查以下问题:
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
以上是 在Windows上,shutil.rmtree失败,显示“访问被拒绝” 的全部内容, 来源链接: utcz.com/qa/404440.html