获取项目根绝对路径,不需要传入项目名称。
发现一个特点,sys.path 中是包含项目根路径
于是这边直接判断:第一个出现和当前执行文件路径重叠的为项目路径。
工具类代码如下:
import sysimport osclass InitUtil: def __init__(self): # print("Init_PathUtil:") self.root_path = self.get_root_path() def get_root_path(self): current_file_path = os.getcwd() project_root_path = None # print("current_file_path:t" + current_file_path) index = 0 for path in sys.path: # print("sys_path%s:ttt" % index + path) index += 1 if current_file_path == path: continue if current_file_path.__contains__(path): project_root_path = path break if project_root_path is None: # 如果未获取到,说明当前路径为根路径 project_root_path = current_file_path # 替换斜杠 project_root_path = project_root_path.replace("\", "/") return project_root_path def printMsg(self, msg): print(" 33[0;36m%s 33[0m" % msg)PathUtil = InitUtil()if "__main__" == __name__: PathUtil.printMsg("RootPath_init:tt" + PathUtil.root_path) # print("n") PathUtil.printMsg("RootPath_func:tt" + PathUtil.get_root_path())测试项目结构
MainTestClass 测试结果:
测试项目Git地址:
https://github.com/cj-8480/PathTest.git
如果有出现问题,欢迎留言。