PYTHON 判断引用路径的类型

PYTHON 判断引用路径的类型

如下方法, 用于实现在不加载模块的前提下, 判断某一个python引用路径是否存在, 以及属于什么类型(模块目录, 模块文件, 类名). 用于在一些不便加载(如项目较大,加载需要额外的环境支持, 或者文件本身较大,加载较慢) 等场景下, 扫描 python 类/模块 是否存在

import ast
import imp

def check_module(module_reference_path):
    def _get_module(module_reference_path):
        if not module_reference_path:
            return None
        module_dict = module_reference_path.split(".")
        module_name = module_dict[-1]
        module_path = "/".join(module_dict[:-1])
        try: 
            mod = imp.find_module(module_name, [module_path])
        except:
            return None
        return mod
    mod = _get_module(module_reference_path)

    # find module not a module, maybe a class or not existed
    if mod is None:
        module_dict = module_reference_path.split(".")
        up_mod = _get_module( ".".join(module_dict[:-1]))
        # check if the upper level is a module, if not, then it not existed
        if up_mod is None or len(module_dict)==1:
            return None
        class_name = module_dict[-1]
        # if upper level is module, then check the if it is a class
        code_body = ast.parse(up_mod[0].read()).body
        for item in code_body:
            if not isinstance(item, ast.ClassDef):
                continue
            if item.name == class_name:
                return "Class"
        return None
    if mod[0] is None:
        return "Module Path"
    return "Module File" 
posted @ 2022-12-04 00:57  coreylin  阅读(54)  评论(0编辑  收藏  举报