[Python Wpg] Import a module using a string

Sydney Weidman syd at plug.ca
Mon Dec 3 19:06:31 EST 2007


This was not obvious to me, so I thought I'd mention it for the benefit
of anyone else who might be trying to do this. I got a bit tired of
using the ConfigParser for loading options and decided that I should
just import a module that could be specified on the command line. But
how can I import a module the name of which I don't know until my script
runs?

I should have guessed that Python has a way to do this. You use the
__import__ builtin function, like so:

import sys

myconfigfile = sys.argv[1]

try:
    config = __import__(myconfigfile)
    for i in config.__dict__:
        print i            
except ImportError:
    print "Unable to import configuration file %s" % (myconfigfile,)

See help(__import__) for more information.

Hope this helps others!

Have a great holiday season!

- Syd






More information about the Winnipeg mailing list