python自動導(dǎo)入包的實現(xiàn)
問題描述: 代碼編寫過程中,需要引入文件,但是引入的文件隨著項目的變大會變多,所以編寫了一個自動導(dǎo)入的方法,會根據(jù)文件名稱的特點進行導(dǎo)入。
def auto_import(packagePath: str, fileTag: str, interceptLength: int, level=1): """ 自動導(dǎo)入函數(shù),導(dǎo)入具有某個標(biāo)識的文件 :param packagePath: 當(dāng)前包路徑 :param level: 軟件包層級 :param fileTag:文件名稱標(biāo)識 :param interceptLength:導(dǎo)入屬性截取名稱 :return: """ # 定義導(dǎo)入屬性列表和包 att_list = [] # 獲取對應(yīng)的包層級 rank = level package = '' for i in range(level): # 獲取父級包名稱拼接包名稱 package += packagePath.split('\\')[-rank] + '.' rank -= 1 # 遍歷當(dāng)前包下的所有文件 for fileName in os.listdir(packagePath): # 篩選出nameTag的文件進行導(dǎo)入 if fileTag in fileName: print(f'導(dǎo)入包名稱:{package}' + fileName[:-3]) # 動態(tài)導(dǎo)入包,并獲取包內(nèi)的具體模塊、屬性 att_list.append( # 導(dǎo)入包中的某個屬性 importlib.import_module( # 拼接模塊路徑 f'{package}' + fileName[:-3] # 獲取模塊中的對應(yīng)屬性 ).__dict__[fileName[:-interceptLength]]) # 返回屬性列表 return att_list
假如我們創(chuàng)建了多個TableModel文件,需要校驗對應(yīng)的文件是否在數(shù)據(jù)庫中存在,那么我們就可以這么用:
import os import auto_import def auto_check_model(): ? ? """ ? ? 導(dǎo)入tableModel中的所有文件,驗證數(shù)據(jù)庫中表是否存在 ? ? :return: 返回驗證結(jié)果 ? ? """ ? ? # 獲取當(dāng)前文件夾路徑 ? ? packagePath = os.path.dirname(os.path.realpath(__file__)) ? ? # 獲取所有model文件 ? ? model_list = auto_import(packagePath=packagePath, fileTag='Model', ?interceptLength=8, level=2) ? ? # 建立數(shù)據(jù)庫連接 ? ? connect = DatabaseOperation().connect() ? ? # 檢查model在數(shù)據(jù)庫中是否存在,不存在則創(chuàng)建 ? ? for i in range(len(model_list)): ? ? ? ? model_list[i].metadata.create_all(connect) ? ? ? ? print(f"#### ? ? {model_list[i].__name__}校驗完成! ? ?####")
到此這篇關(guān)于python自動導(dǎo)入包的實現(xiàn)的文章就介紹到這了,更多相關(guān)python自動導(dǎo)入包內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
極簡Python庫CherryPy構(gòu)建高性能Web應(yīng)用實例探索
今天為大家介紹的是 CherryPy,它是一個極簡、穩(wěn)定且功能強大的Web框架,可以幫助開發(fā)者快速構(gòu)建高性能的 Web 應(yīng)用程序,使用 CherryPy,你可以輕松地創(chuàng)建RESTful API、靜態(tài)網(wǎng)站、異步任務(wù)和 WebSocket 等應(yīng)用2024-01-01