From 35450fefe2287015870089ae6ca3d3e51ccceadd Mon Sep 17 00:00:00 2001 From: clinton-hall Date: Wed, 25 Jun 2014 09:33:47 +0930 Subject: [PATCH] add error handling to cleandir to handle "read only" files. Fixes #445 --- nzbtomedia/nzbToMediaUtil.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/nzbtomedia/nzbToMediaUtil.py b/nzbtomedia/nzbToMediaUtil.py index 6fb5cca0..907802ee 100644 --- a/nzbtomedia/nzbToMediaUtil.py +++ b/nzbtomedia/nzbToMediaUtil.py @@ -543,10 +543,28 @@ def getDirs(section, subsection): return list(set(to_return)) +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)`` + """ + if not os.access(path, os.W_OK): + # Is the error an access error ? + os.chmod(path, stat.S_IWUSR) + func(path) + else: + raise + def rmDir(dirName): logger.info("Deleting %s" % (dirName)) try: - shutil.rmtree(dirName, True) + shutil.rmtree(dirName, onerror=onerror) except: logger.error("Unable to delete folder %s" % (dirName)) @@ -569,7 +587,10 @@ def cleanDir(path, section, subsection): 'CLEANDIRS') logger.info("Directory %s has been processed, removing ..." % (path), 'CLEANDIRS') - shutil.rmtree(path) + try: + shutil.rmtree(path, onerror=onerror) + except: + logger.error("Unable to delete directory %s" % (dirName)) def create_torrent_class(clientAgent): # Hardlink solution for Torrents