栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python动态加载py文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python动态加载py文件

import importlib
import sys
import types



# 判断是不是方法
def is_function(tup):
    """ Takes (name, object) tuple, returns True if it is a function.
    """
    name, item = tup
    return isinstance(item, types.FunctionType)

# 判断是不是类
def is_variable(tup):
    """ Takes (name, object) tuple, returns True if it is a variable.
    """
    name, item = tup
    if callable(item):
        # function or class
        return False

    if isinstance(item, types.ModuleType):
        # imported module
        return False

    if name.startswith("_"):
        # private property
        return False

    return True

def load_python_module(file_path):
	""" load python module.
	
	Args:
	    file_path: python path
	
	Returns:
	    dict: variables and functions mapping for specified python module
	
	        {
	            "variables": {},
	            "functions": {}
	        }
	
	"""
	debugtalk_module = {
	    "variables": {},
	    "functions": {}
	}
	
	sys.path.insert(0, file_path)
	module = importlib.import_module("debugtalk")
	# 修复重载bug
	importlib.reload(module)
	sys.path.pop(0)
	
	for name, item in vars(module).items():
	    if is_function((name, item)):
	        debugtalk_module["functions"][name] = item
	    elif is_variable((name, item)):
	        if isinstance(item, tuple):
	            continue
	        debugtalk_module["variables"][name] = item
	    else:
	        pass
	
	return debugtalk_module





转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/580846.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号