Python importlib動態(tài)導(dǎo)入模塊實現(xiàn)代碼
閱讀目錄
一般而言,當(dāng)我們需要某些功能的模塊時(無論是內(nèi)置模塊或自定義功能的模塊),可以通過import module 或者 from * import module的方式導(dǎo)入,這屬于靜態(tài)導(dǎo)入,很容易理解。
而如果當(dāng)我們需要在程序的運行過程時才能決定導(dǎo)入某個文件中的模塊時,并且這些文件提供了同樣的接口名字,上面說的方式就不適用了,這時候需要使用python 的動態(tài)導(dǎo)入。
importlib使用
如在scripts目錄中保存著一些功能模塊,向外提供類似的接口poc()和腳本描述信息description,需要傳入一個參數(shù)target,當(dāng)然腳本執(zhí)行的功能是不一樣的,以下只是舉例:
starnight:EXP-M starnight$ ls scripts/__init__.py __pycache__ test1.py test2.py test3.pystarnight: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 importlibscript_name = input(’please input script_name : ’) # 手動輸入腳本名 module = importlib.import_module(’scripts.{}’.format(script_name))# 動態(tài)導(dǎo)入相應(yīng)模塊func = module.poc(’’)# 執(zhí)行腳本功能print(module.description) # 獲取腳本描述信息
please input script_name : test1it is a test1it is a test1...please input script_name : test3it is a test3it is a test3
當(dāng)我們動態(tài)給定腳本名字時,就會動態(tài)的導(dǎo)入該模塊,執(zhí)行相應(yīng)的功能。
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.'當(dāng)進行編程時,使用import_module,如上使用該模塊。
find_loader用來查找模塊,reload重新載入模塊,invalidate_caches不多介紹了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp3. php測試程序運行速度和頁面執(zhí)行速度的代碼4. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析6. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析8. ASP中常用的22個FSO文件操作函數(shù)整理9. SharePoint Server 2019新特性介紹10. 三個不常見的 HTML5 實用新特性簡介
