Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Python module from memory [duplicate]

Tags:

python

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

I have some Python file in the memory that may be StringIO. How can I import module file stored in the memory? I do not want to save it to disk and then load.

It looks like:

import StringIO.StrngIO([buf]) 
like image 708
simon Avatar asked Jan 07 '13 07:01

simon


People also ask

Does Python import module twice?

The module is only loaded the first time the import statement is executed and there is no performance loss by importing it again.

What happens if you import a module twice?

If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules.

Can we import a module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

How many times does a module get loaded when imported multiple times?

A module code is evaluated only the first time when imported. If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers. The one-time evaluation has important consequences, that we should be aware of.


1 Answers

A nice approach is to use custom Meta import hooks as described in PEP 302. One can write a class that imports modules dynamically from a dictionary of strings:

"""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()

BTW: If you don't want that much and just want to import one string, then stick to the implementation of the method load_module. All you need is inside it.

like image 179
Thorsten Kranz Avatar answered Sep 24 '22 11:09

Thorsten Kranz