Import a module from a non-file?

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sat Oct 18 06:28:26 EDT 2003


Petri Savolainen wrote:

> I was trying to roll my own python code importer, but in the end, it seems
> that no matter what you try, it is always necessary to supply a REAL file
> object for python lower-level import machinery to work. Is this really
> true? Or did I miss something?

Probably, because I have been importing modules from over a network
socket for a long time now in Pyro. (http://pyro.sourceforge.net)

The code in Pyro works back to python version 2.0, if I'm not mistaken,
so you won't need to upgrade to 2.3 and use all new kinds of import hooks...

Basically what I'm doing is
* load the module's bytecode over the network
* create a new module and put it in sys.modules using new.module(...)
* execute the downloaded code in this new module: exec code in mod.__dict__
* some extra magic to trap cascaded imports.

If you need more info, have a look at the _retrieveCode method
in the protocol.py file of Pyro, or just ask :)

I'm not sure if my way of doing things is the 'best' way, but hey,
it works... :)

--Irmen de Jong





More information about the Python-list mailing list