Python项目模块找不到路径问题
此篇仅作为工作是遇到问题的记录,不进行任何阐述
工作问题:
模块无法正确找到路径,也就是sys.path里面没有当前模块路径,所以导致导包出错,索性写个小函数,将当前项目的所有文件夹都加入sys.path模块,一劳永逸
添加到sys.path
rootpath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.extend([rootpath, ])
from libs.find_path import extend_path
syspath = sys.path
sys.path.extend(extend_path([rootpath, ]))
sys.path.extend(syspath)
extend_path函数
import os
PATHList = []
DirFlag = 1
def extend_path(tlist):
"""
寻找路径函数,解决单独模块找不到路径问题
:param tlist: -> list of path
:return: -> if has dir then return dir list; else return final path list
"""
global PATHList
global DirFlag
PATHList += tlist
if DirFlag == 0:
return PATHList
ttlist = []
DirFlag = 0
for i in tlist:
for data in os.listdir(i):
tpath = os.path.join(i, data)
if os.path.isdir(tpath) and '__pycache__' not in tpath and 'migrations' not in tpath:
ttlist.append(tpath)
DirFlag = 1
return extend_path(ttlist)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
有任何问题请随时交流~
Email: araise1@163.com