2012-05-29 24 views
5

我對此上測試下面的代碼的一個問題:何時在python中釋放函數堆棧數據?

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. 文件對象時關閉file_close_test退出,因爲沒有參考它。
  2. 發生異常後,文件對象沒有關閉,所以我認爲相關的堆棧數據沒有發佈。
  3. exception_wrapper退出,文件自動關閉。

你能解釋一下這個給我嗎?謝謝。

回答

3

異常包括可用於訪問在任何疊層的所有的局部變量的時拋出異常幀活性回溯對象。這意味着您仍然可以訪問該文件,直到清除異常上下文爲止。

即使是sleep()exception_wrapper結束後,你可以使用sys.exc_info獲得在打開的文件是這樣的:

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

所有這一切當然是特定於您所使用的特定Python實現。其他實現可能不會隱式關閉文件,直到它們被垃圾收集爲止。

底線是你永遠不應該依靠Python的引用計數或垃圾收集來清理資源,比如打開文件,總是明確地做。

+1

這也不難:'開放('/ tmp/test','w +')爲f:' –

+0

它幫助我很多,謝謝:) – yancl