栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从内存中导入Python模块

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

从内存中导入Python模块

一种不错的方法是使用PEP 302中所述的自定义元导入挂钩。可以编写一个从字符串字典动态导入模块的类:

"""Use custom meta hook to import modules available as strings. Cp. PEP 302 http://www.python.org/dev/peps/pep-0302/#specification-part-2-registering-hooks"""import sysimport impmodules = {"a" : """def hello():    return 'Hello World A!'""","b":"""def hello():    return 'Hello World B!'"""}class Stringimporter(object):   def __init__(self, modules):       self._modules = dict(modules)   def find_module(self, fullname, path):      if fullname in self._modules.keys():         return self      return None   def load_module(self, fullname):      if not fullname in self._modules.keys():         raise importError(fullname)      new_module = imp.new_module(fullname)      exec self._modules[fullname] in new_module.__dict__      return new_moduleif __name__ == '__main__':   sys.meta_path.append(Stringimporter(modules))   # Let's use our import hook   from a import hello   print hello()   from b import hello   print hello()

顺便说一句:如果您不想太多,而只想导入一个字符串,那么请坚持执行load_module方法。您只需要在里面。



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

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

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