Loading a Python module from file

April 5th, 2012

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 as feature, 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.

in Python

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam protection by WP Captcha-Free