ANN: experimental patch to allow importing from file-like objects
Gordon McMillan
gmcm at hypernet.com
Sat Mar 2 07:30:42 EST 2002
Gerson Kurz wrote:
> Motivation: Write a customized import that reads data from encrypted
> files. Both execfile() and exec() are limited, if only that that they
> don't mimic the import syntax.
>
> Problem: imp.load_module does expect a file object, but you can only
> pass "real" files, not file-like objects. The internal C-code expects
> native FILE* stuff.
>
> Solution: An experimental patch to the python22.dll that makes this
> possible. Using file-like objects for import opens up a whole new set
> of possibilities, for example you could fetch the code at runtime from
> a database or a socket.
Most people doing something like this don't use imp.load_module.
First you need a code object for the module. If it's source:
co = compile(open(srcfile, 'r').read()+'\n', srcfile, 'exec')
If it's already compiled (and still fresh etc.)
stuff = open(bytecodefile, 'rb').read()
co = marshal.loads(stuff[8:])
Then you need a module object
mod = imp.new_module(nm)
(You need to set up mod.__file__, mod.__name__ etc. here).
And finally
sys.modules[fqname] = mod
exec co in mod.__dict__
This is not to say that I'm against your patch (didn't look
at it), just that there's another way around the problem.
-- Gordon
http://www.mcmillan-inc.com/
More information about the Python-list
mailing list