侧边栏壁纸
博主头像
996worker

祇園精舎の鐘の聲, 諸行無常の響き有り。

  • 累计撰写 159 篇文章
  • 累计创建 44 个标签
  • 累计收到 6 条评论

A useful util for Python to get project path

996worker
2022-03-19 / 0 评论 / 0 点赞 / 53 阅读 / 1,098 字
温馨提示:
本文最后更新于 2022-03-19,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
# desc: get root path

import sys
import os

from src.util.singleton_decorator import singleton


@singleton
class PathUtil(object):
    """tools for get project root path"""

    def __init__(self):
        # 判断调试模式
        debug_vars = dict((a, b) for a, b in os.environ.items()
                          if a.find('IPYTHONENABLE') >= 0)
        # 根据不同场景获取根目录
        if len(debug_vars) > 0:
            """当前为debug运行时"""
            self.__rootPath = sys.path[2]
        elif getattr(sys, 'frozen', False):
            """当前为exe运行时"""
            self.__rootPath = os.getcwd()
        else:
            """正常执行"""
            self.__rootPath = sys.path[1]
        # 替换斜杠
        self.__rootPath = self.__rootPath.replace("\\", "/")

    def get_root_path(self):
        return self.__rootPath


if __name__ == '__main__':
    """test"""
    # path = PathUtil.getPathFromResources("context.ini")
    PathUtil = PathUtil()
    print(PathUtil.get_root_path())

Note: @singleton is decorator of singleton, the code is below:

# desc: Quick decorator for singleton pattern

def singleton(cls, *args, **kw):
    __instance = {}

    def get_instance():
        if cls not in __instance:
            __instance[cls] = cls(*args, **kw)
        return __instance[cls]

    return get_instance

0

评论区