Dynamically loading modules in Python

October 19th, 2007

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')
sys.path.append(googlebot_mod_dir)
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!

Clever advertising

July 5th, 2007

New Heroes flowchart!

May 8th, 2007

Heroes relationship flowchart

February 27th, 2007

Best burger ever

December 16th, 2006

Two Stargate SG-1 movies confirmed

October 11th, 2006

Second Stargate movie on it’s way?

August 20th, 2006

Phil Gordon comes to Google!

August 13th, 2006

Our new puppy

July 11th, 2006

Net Neutrality in the Senate

June 12th, 2006