Python動態載入模組

2022-08-28 19:24:09 字數 1300 閱讀 5346

需求:實現乙個簡單的pyton程式,接收兩個引數:plugin_name, data,根據不同的plugin_name定位到不同的邏輯處理模組並進行輸出。

實現方案:

使用python的庫函式:load_source,將外掛程式模組載入到乙個dict中key為模組名稱,value為類的例項,核心**:

def

load_plugins():

global

plugin_dict

#遍歷外掛程式目錄載入所有py結尾的模組

for root, dirs, files in

os.walk(module_path):

for file in

files:

if file.endswith('

.py'

): module_name = file[:-3]

print

module_name

module_file_path =os.path.join(root, file)

module =load_source(module_name, module_file_path)

#判斷外掛程式中是否存在handler類if'

handler'in

dir(module):

print

'load module: %s

' %module_name

#初始化類的例項並存入dict中,

clazz =getattr(module, class_name)

clazz_instance =clazz()

plugin_dict.update()

外掛程式**樣例:

#

統一的類

class

handler:

#統一的處理介面

defparse(self, data):

print

data

result =

return json.dumps(result)

呼叫**:

#

根據plugin找到對應的例項

clazz_instance =plugin_dict[plugin]

try:

ret =clazz_instance.parse(data_obj)

return

ret

except

exception,e :

print traceback.format_exc()

Python模組的動態載入機制

python在執行環境初始化中,就將sys module載入到了記憶體中,實際上,python是將一大批的module載入到了記憶體中。但是為了使local名字空間能夠達到最乾淨的效果,python並沒有將這些符號暴露在當前的local名字空間中,而是需要使用者顯式的通過import機制通知pyth...

Lua動態載入模組

function reload modulename package.loaded modulename nil require modulename end 使用以上 即可重新載入乙個檔案。這樣修改完lua 後,可以不用重啟程式立刻生效。模組a a function a.test1 print 1...

nginx載入動態模組

不使用動態模組時 使用動態模組 不是所有的nginx模組都可以以動態模組方式加入nginx 載入方式參見nginx模組載入 需要注意的是 with http image filter module dynamic 如果採用動態模組的載入方式,那麼需要將 usr local src nginx 1.8...