"""Script demonstrating close regression with weakref change Prints nothing on earlier versions, but with Python 2.7 outputs similar to: Error in atexit._run_exitfuncs: Traceback (most recent call last): File "python-trunk/lib/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "python-trunk/lib/logging/__init__.py", line 1615, in shutdown h.flush() File "python-trunk/lib/logging/__init__.py", line 824, in flush self.stream.flush() ValueError: I/O operation on closed file Error in sys.exitfunc: Traceback (most recent call last): File "python-trunk/lib/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "python-trunk/lib/logging/__init__.py", line 1615, in shutdown h.flush() File "python-trunk/lib/logging/__init__.py", line 824, in flush self.stream.flush() ValueError: I/O operation on closed file """ import os, atexit _ref_list = [] # Keep this list alive till the atexit function runs atexit.register(lambda _=_ref_list: None) import logging def register_handler(): """Create, add, remove, and close a handler, and return it""" f = open(os.devnull, "w") handler = logging.StreamHandler(f) logger = logging.getLogger("test") logger.addHandler(handler) logger.removeHandler(handler) # Closing the handler now does nothing in Python 2.7 so... handler.close() # ...closing the underlying file is now unsafe f.close() return handler if __name__ == "__main__": # Reference held anywhere that outlives logging atexit shutdown _ref_list.append(register_handler())