[Tutor] using dynamic import statements
Chris Hare
chare at labr.net
Mon Jul 9 03:10:10 CEST 2012
Here is what I want to do:
I have a bunch of modules to import. instead of duplicating a lot of code for each import, I want to do something like this:
importList = [ "sys", "os", "imp", "stat", "re", "webbrowser", "Image", "StringIO", "shutil", "datetime" ]
for object in importList:
try:
if debug == "ON":
print "Importing module %s" % (object)
exec( "import " + object)
except ImportError as error:
print "%s %s requires the Python %s library. " % ( appName,
str(appVersion), object )
print "An error occurred when attempting to load the library. The error was '%s'." % ( error )
exit()
Everything "appears" to run okay, however, when the first piece of code that relies upon one of these imported modules is executed, I get an error:
Traceback (most recent call last):
File "a.py", line 122, in <module>
imp.load_module(object,fp,pathName,description)
File "./Modules/functions.py", line 133, in <module>
def special_match(strg, search=re.compile(r'[^a-zA-Z0-9\.\ \-\#\$\*\@\!\%\^\&]').search):
NameError: name 're' is not defined
Is is possible to do what I am trying to do, or am I doing something wrong?
Thanks
More information about the Tutor
mailing list