您好,登錄后才能下訂單哦!
小編這次要給大家分享的是如何實現(xiàn)Python importlib動態(tài)導入模塊,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
閱讀目錄
一般而言,當我們需要某些功能的模塊時(無論是內(nèi)置模塊或自定義功能的模塊),可以通過import module 或者 from * import module的方式導入,這屬于靜態(tài)導入,很容易理解。
而如果當我們需要在程序的運行過程時才能決定導入某個文件中的模塊時,并且這些文件提供了同樣的接口名字,上面說的方式就不適用了,這時候需要使用python 的動態(tài)導入。
importlib使用
如在scripts目錄中保存著一些功能模塊,向外提供類似的接口poc()和腳本描述信息description,需要傳入一個參數(shù)target,當然腳本執(zhí)行的功能是不一樣的,以下只是舉例:
starnight:EXP-M starnight$ ls scripts/ __init__.py __pycache__ test1.py test2.py test3.py starnight:EXP-M starnight$ cat scripts/test1.py #!/usr/bin/env python # -*- coding:utf-8 -*- description = 'it is a test1' def poc(target): print('it is a test1') return True
而我們需要動態(tài)傳入腳本名,來選用此時要執(zhí)行的功能:
#!/usr/bin/env python # -*- coding:utf-8 -*- import importlib script_name = input('please input script_name : ') # 手動輸入腳本名 module = importlib.import_module('scripts.{}'.format(script_name)) # 動態(tài)導入相應模塊 func = module.poc('') # 執(zhí)行腳本功能 print(module.description) # 獲取腳本描述信息
please input script_name : test1 it is a test1 it is a test1 ... please input script_name : test3 it is a test3 it is a test3
當我們動態(tài)給定腳本名字時,就會動態(tài)的導入該模塊,執(zhí)行相應的功能。
importlib其他介紹
python doc: importlib
importlib中的幾個函數(shù):__import__、import_module、find_loader、invalidate_caches、reload
"Note Programmatic importing of modules should use import_module() instead of this function."
當進行編程時,使用import_module,如上使用該模塊。
find_loader用來查找模塊,reload重新載入模塊,invalidate_caches不多介紹了。
看完這篇關于如何實現(xiàn)Python importlib動態(tài)導入模塊的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。