[Tutor] using dynamic import statements
Hugo Arts
hugo.yoshi at gmail.com
Mon Jul 9 08:57:50 CEST 2012
On Mon, Jul 9, 2012 at 3:10 AM, Chris Hare <chare at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120709/e67d2948/attachment.html>
More information about the Tutor
mailing list