Windows에서 shutil.rmtree가 '액세스가 거부되었습니다'와 함께 실패합니다.
이 질문에 이미 답변이 있습니다.
- Python 6 답변 에서 디렉토리 삭제
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/
무엇입니까? (unxutils 또는 cygwin과 같은 타사 도구를 사용할 필요 없음-이 코드는 PyWin32가 설치된 Python 2.6이 설치된 베어 Windows 설치에서 실행되는 것을 목표로합니다)
이 질문을 확인하십시오.
Windows에서 Python 스크립트를 실행하는 사용자는 무엇입니까?
분명히 대답은 파일 / 폴더를 읽기 전용이 아닌 것으로 변경 한 다음 제거하는 것입니다.
댓글에서 @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
삭제를 시도하기 전에 각 파일에서 os.chmod 를 사용하여 액세스를 보장 하는 os.walk로 자신의 rmtree를 구현한다고 말하고 싶습니다 .
다음과 같은 것 (예상되지 않음) :
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)
글쎄, 표시된 솔루션이 나를 위해 작동하지 않았습니다 ... 대신 이렇게했습니다.
os.system('rmdir /S /Q "{}"'.format(directory))
shutil.rmtree(path,ignore_errors=False,onerror=errorRemoveReadonly)
def errorRemoveReadonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
# change the file to be readable,writable,executable: 0777
os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
# retry
func(path)
else:
raiseenter code here
If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.enter code here
A simple workaround is using subprocess.call
from subprocess import call
call("rm -rf build/", shell=True)
In order to execute everything you want.
참고URL : https://stackoverflow.com/questions/2656322/shutil-rmtree-fails-on-windows-with-access-is-denied
'Nice programing' 카테고리의 다른 글
Ansible-로컬 환경 변수에 액세스 (0) | 2020.11.27 |
---|---|
C # 7.0은 .NET 4.5에서 작동합니까? (0) | 2020.11.27 |
실행 취소 / 다시 실행 구현 (0) | 2020.11.27 |
블러 이벤트를 수동으로 추적하지 않고 Backbone.js의 모델에 양식 입력을 바인딩 할 수 있습니까? (0) | 2020.11.27 |
결과가 하나만있을 경우 목록 이해의 대안 (0) | 2020.11.27 |