import thread, time, os, tempfile fname = tempfile.mktemp() f = open(fname, 'w', buffering=1024*1024) def sneaky_close(): global f while True: time.sleep(0.01) print 'closing' try: f.close() except IOError: pass lst = [1] * 1024 * 1024 for i in lst: pass print 'closed' f = open(fname, 'w', buffering=1024*16) thread.start_new_thread(sneaky_close, ()) big = 'z'*1024*4 while True: try: print 'write call' f.write(big) f.flush() print 'write returned' except ValueError: pass