Context:
I am using shutil.rmtree
(delDir, ignore_errors = False, onerror = readOnlyErrorHandler)
to delete a directory tree that holds readonly files:
Annoyence: PyLint (inside VS Code) marks the raise
command inside my readOnlyErrorHandler
function as
Question: Is there a way around getting this warning without disabling linting for the whole file?
def readOnlyErrorHandler(func, path, exc_info):
import errno
if func in (os.rmdir, os.unlink, os.remove) and exc_info[1].errno == errno.EACCES:
print (f"Retry '{func.__name__}' after chmod 0o777 on '{path}'")
os.chmod(path, 0o777)
func(path)
else:
# marked as 'The raise statement is not inside an except clause'
# by pylint(misplaced-bare-raise)
raise # purpose: rethrow the other errors that brought me here
System: Windows, Python 3.6.3
Test with:
from stat import S_IREAD, S_IRGRP, S_IROTH
import os
import shutil
path = "./some/path/to/files/"
# create read only files:
os.makedirs(path, exist_ok=True)
for fn in ["one.txt","two.txt"]:
filename = os.path.join(path, fn)
with open(filename, "w") as f:
f.write("read only")
os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)
# try to delete files
# fails: shutil.rmtree(path)
# works
shutil.rmtree(path, ignore_errors=False, onerror=readOnlyErrorHandler)
you have all the information about the exception that occurred in exc_info
. in this case exc_info
will be something like
(
<class 'FileNotFoundError'>,
FileNotFoundError(2, 'No such file or directory'),
<traceback object at 0x7fae2a66a0c8>
)
so you could either re-raise the exception with
raise exc_info[1]
or customize the error messsge (but keep the type of the exception):
raise exc_info[0]("exception from readOnlyErrorHandler")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With