On Mon, Jul 9, 2012 at 3:10 AM, Chris Hare <ch...@labr.net> wrote: > > 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? > > Yes, it is possible, but you are doing something wrong. Don't use exec() for this, it's unnecessary. You can make this work with the exec function, but the function you really want is called __import__(). It's documented here: http://docs.python.org/library/functions.html#__import__
HTH, Hugo
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor