Python: importing a module from memory

Possible duplicate:
How to load compiled python modules from memory?

I have a python file in memory, which can be StringIO.I, how to import a module file stored in memory. I do not want to save it to disk and load.

It looks like this:

import StringIO.StrngIO([buf]) 
+1
source share
1 answer

A good approach is to use custom meta-import hooks as described in PEP 302 . You can write a class that dynamically imports modules from a string dictionary:

 """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 use our import hook from a import hello print hello() from b import hello print hello() 

BTW: If you do not want this and want to import a single line, then stick to the implementation of the load_module method. All you need is inside it.

+6
source

All Articles