The importer stored in the cStringIO data structure and the physical disk file
Is there a way to import a Python module stored in a cStringIO data structure or a physical disk file?
It looks like "imp.load_compiled (name, pathname [, file])" is what I need, but the description of this method (and similar methods) has the following disclaimer:
Quote: "The file argument is a file of byte compiled code, open for reading in binary mode from the start. It must be a real file object, not a user-defined class that emulates the file." [1]
I tried using a cStringIO object against a real file object, but the reference documentation is correct - only the real file can be used.
Any ideas as to why these modules impose such a limitation or is it just a historical artifact?
Are there any methods I can use to avoid this physical file requirement?
Thanks, Malcolm
a source to share
Is something like this possible?
import types
import sys
src = """
def hello(who):
print 'hello', who
"""
def module_from_text(modulename, src):
if modulename in sys.modules:
module = sys.modules[modulename]
else:
module = sys.modules[modulename] = types.ModuleType(modulename)
exec compile(src, '<no-file>', 'exec') in module.__dict__
return module
module_from_text('flup', src)
import flup
flup.hello('world')
What prints:
hello world
EDIT
Evaluating code this way moves closer to the realm of writing custom importers. It might be helpful to look at PEP 302 and Doug Hellmann PyMOTW: Modules and Imports .
a source to share