I find myself often in the situation, where I need to load a particular Python file as module.
For instance when working on a particular system, and I don’t want to overshadow all modules in one directory with all the files in my development copy. So using
sys.path and appending my workspace directory to it won’t work.
Instead, one can use the
imp module, which provides the very useful
load_source() function. Here’s an example:
import imp theModule = imp.load_source("theModule", "/path/to/the/file/theModule.py")The first parameter is the name, under which the module will be registered to Python. I suppose the idea is the same as importing with the
asfeature, where you can rename a module, but Python still needs to know what the module’s real name is, in order to avoid loading the same module twice, etc.
The result of the call is the module object, which can then be used as any other module in Python.