Question

I have a question about this on testing the following code:

1,

def file_close_test():
    f = open('/tmp/test', 'w+')

if __name__ == '__main__':
    file_close_test()
    # wait to see whether file closed.
    import time
    time.sleep(30)

2,

def file_close_on_exc_test():
    f = open('/tmp/test', 'w+')
    raise Exception()

def exception_wrapper():
    try:
        file_close_on_exc_test()
    except:
        pass
    # wait to see whether file closed.
    import time
    time.sleep(10)

if __name__ == '__main__':
    exception_wrapper()
    import time
    time.sleep(30)
  1. The file object closed when the file_close_test exits because no reference to it.
  2. After the exception raised,the file object not closed.so i think the related stack data not released.
  3. After exception_wrapper exit,the file closed automatically.

can you explain this for me? thanks.

Was it helpful?

Solution

The exception includes a traceback object which can be used to access all of the local variables in any of the stack frames active when the exception was thrown. That means you can still access the file until the exception context is cleared.

Even after the sleep() at the end of exception_wrapper you could use sys.exc_info to get at the open file like this:

tb = sys.exc_info()[2]
print tb.tb_next.tb_frame.f_locals['f']

All of this is of course specific to the particular Python implementation you are using. Other implementations may not implicitly close files at all until they are garbage collected.

The bottom line is you should never depend on Python's reference counting or garbage collection to clean up resources like open files, always do it explicitly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top