您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从内存中导入Python模块

从内存中导入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 sys
import imp

modules = {"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_module


if @R_403_1211@ == '__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方法。您只需要在里面。

python 2022/1/1 18:39:55 有270人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶