2009-02-20 84 views
7

我有一個模塊使用ctypes將一些功能從靜態庫包裝到類中。當模塊加載時,它會在靜態庫中調用一個初始化函數。當模塊被卸載時(大概是解釋器退出時),我希望在庫中有一個卸載函數。我怎樣才能創建這個鉤子?當Python模塊卸載時檢測到

回答

13

使用atexit模塊:

import mymodule 
import atexit 

# call mymodule.unload('param1', 'param2') when the interpreter exits: 
atexit.register(mymodule.unload, 'param1', 'param2') 

從文檔的另一個簡單的例子,使用register作爲裝飾:(?)

import atexit 

@atexit.register 
def goodbye(): 
    print "You are now leaving the Python sector." 
+0

atexit對可以是不方便/不潔溶液,特別是如果過程分叉等。也許最好跳過魔術並提供模塊用戶應該調用的「清理」/終結函數? – u0b34a0f6ae 2010-05-12 08:20:39