The normal way to load Python code is through the import statement:
import pprint
pprint.pprint('Hello, world.')
But what do you do if you want to dynamically load a module? A classic example of where you’d like to do this is adding ‘extensions’ to your application. Your application has no way of knowing the exact name of the module that it’s going to use; it only knows the filename(s). The way to do this is the imp module:
import md5
import os.path
import imp
import traceback
def load_module(code_path):
try:
try:
code_dir = os.path.dirname(code_path)
code_file = os.path.basename(code_path)
fin = open(code_path, 'rb')
return imp.load_source(md5.new(code_path).hexdigest(), code_path, fin)
finally:
try: fin.close()
except: pass
except ImportError, x:
traceback.print_exc(file = sys.stderr)
raise
except:
traceback.print_exc(file = sys.stderr)
raise
A few notes:
- call
load_modulewith the path to a.pyfile that you want to load - the
md5.newgenerates a unique module identifier. If you don’t do this it’s difficult to import two modules in different directories with the same name! - the different
excepts are to give you a flavor of the issues you may see,ImportErroris expected, the others are not
The return value is a module, which is a Python object that you can address in all the normal ways that you’d use a module. For example, if you have the following file extension.py:
def hello(x): print "Hello, %s" % x
You can use it as follows to get Hello, world.
m = load_module('extension.py')
m.hello("World")
Very cool stuff. I am writing a log parser GUI program right now and wanted the ability to load “parsers” by monitoring a directory and then loading the parser’s… Very very cool.. just what I was looking for! If you are in the market to work on some pygtk + glade gui python stuff please stop by my site I am posting tutorials on how to do so… also will make sure to give you some props..
Riley
Same as Riley.
It was what I was looking for!
Many thanks for sharing the knowledge.
Thanks a lot, a great, simple post!
exactly what I need thanks.
I guess code_file and code_dir are leftovers as they are not used.
LOL … probably artifacts from a debugging session.