【问题标题】:Import Python module from memory [duplicate]从内存中导入 Python 模块 [重复]
【发布时间】:2013-01-07 07:51:26
【问题描述】:

可能重复:
How to load compiled python modules from memory?

我在内存中有一些 Python 文件,可能是 StringIO。如何导入存储在内存中的模块文件?我不想将它保存到磁盘然后加载。

看起来像:

import StringIO.StrngIO([buf]) 

【问题讨论】:

标签: python


【解决方案1】:

一个不错的方法是使用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 __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 的实现。你所需要的就在它里面。

【讨论】:

  • 这将如何与包一起使用?谢谢
  • 不确定...包基本上是模块的集合。也许在导入期间玩弄名称可能会带来导入包的错觉。你的用例是什么?
  • @ThorstenKranz 在 Python 3 中,为什么我会得到这个 exec(self._modules[fullname] in new_module.__dict__) TypeError: exec() arg 1 must be a string, bytes or code object?我对 Python 3 进行了必要的更改(将 print 和 exec 括在括号内)
猜你喜欢
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多