When to release function stack data in python?

I have a question about this when 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)
  • The file object is closed when file_close_test completes because it does not reference it.
  • After an exception occurs, the file object is not closed. It seems to me that the associated stack data is not released.
  • After the exception_wrapper exits, the file closes automatically.

Can you explain this to me? thank.

+5
source share
1 answer

, , . , , .

sleep() exception_wrapper sys.exc_info :

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

, , Python, . , .

Python , , , .

+3

All Articles