Dynamically loading modules in Python

Have you wanted to load modules, when you didn’t know their name?

I recently came across this problem while refactoring GoogleBot (my IRC bot). I wanted to place loadable modules in a directory, and have them all loaded, without having to know what they are named.

A good fellow called Issac at work helped me with this:

import imp
googlebot_mod_dir = os.path.abspath('modules')
for module_file in os.listdir(googlebot_mod_dir):
module_name, ext = os.path.splitext(module_file)
if ext == '.py':
module_location = imp.find_module(module_name)
module = imp.load_module(module_name, *module_location)
globals()[module_name] = module

Works like a charm!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top