I wrote a context manager to suppress OSError based on errno value. Here, this context manager simply rewrote a bit to catch WinError .
Your sample code prints a message when an error occurs, but it does not print anything; he silently suppresses the exception.
I did not test this because I do not have Windows, but I tested the original and this is a trivial editing. Let me know if you have a problem with this.
The function of the .__exit__() method receives information about any exceptions received, and if it returns True , the exception is suppressed; if it returns False , the exception is expressed as usual. Thus, this only suppresses the exception if the type matches (it was a WinError exception), and the .errno attribute matches the stored value of self.errno .
class suppress_winerror(object): def __init__(self, errno): self.errno = errno def __enter__(self): return self def __exit__(self, e_type, e_val, e_tb): if e_type is not WinError: return False if e_val.errno != self.errno: return False return True
An example of using this. I assume that the Windows error code is displayed on errno.EEXIST , the errno code for "file already exists". Obviously, if I am mistaken, you must enter the correct error code.
import errno with suppress_winerror(errno.EEXIST): os.rename(old_fname, new_fname)
source share