#!/usr/bin/env python3 # This demonstrates __enter__/__exit__ being disrupted in NamedTemporaryFile, # resulting in files that are never cleaned up. # # Tested on Linux import os import zipfile import tempfile import threading import signal import time def sigint_thread(): """Simulates several rapid Ctrl+C presses. It makes this demo more reliable than making the user spam Ctrl+C You might need to adjust the sleep() times a bit for your system.""" pid = os.getpid() time.sleep(0.1) for i in range(20): time.sleep(0.2) os.kill(pid, signal.SIGINT) # Simulate Ctrl+C # Make a zip file with a big file in it with zipfile.ZipFile('test.zip', 'w', zipfile.ZIP_DEFLATED) as zf: with zf.open('test.dat', 'w') as fp: fp.write(os.urandom(1024)*1024) zf = zipfile.ZipFile('test.zip', 'r') fp = zf.open('test.dat') sigint = threading.Thread(target=sigint_thread) sigint.start() while True: try: if not fp.read(1): fp.seek(0) # rewind except KeyboardInterrupt: print("ouch") sigint.join()