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"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端