I'm using the output suppression contextmanager described in charleslparker's answer to this question: How to suppress console output in Python? - this works beautifully, but it's nested in a larger block of code (snippet below) dedicated to downloading files from a specific website, which utilizes a higher-level try/except block to catch connection errors. This should be simple, as described in a_guest's beautiful answer to this similar question: Catching an exception while using a Python 'with' statement - however, my problem is that I have an extra block of code (specifically, checking for matching file sizes locally and on the website) that needs to execute upon successful completion of the download, which is getting called every time the ConnectionError exception is raised. Basically, the exception registered within the contextmanager does not propagate upwards correctly, and the code deletes the partial files before restarting the process. I want the exception encountered by the download within the context manager to skip straight to the explicit exception block, and I am totally stuck on how to force that.
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
except (ConnectionErrorType1, ConnectionErrorType2):
raise ConnectionError()
finally:
sys.stdout = old_stdout
while True:
try:
with suppress_stdout():
<download from the website>
if check_file_sizes:
<get target file size>
if download_size != target_size:
<delete files and try again>
except ConnectionErrorType1:
<print error-specific message>
raise ConnectionError()
except ConnectionErrorType2:
<print error-specific message>
raise ConnectionError()
except:
print("Something happened but I don't know what")
raise ConnectionError()
Any and all insight is appreciated, and I'm happy to provide further context or clarification as needed.