importing files from a directory

Thomas Guettler guettli at thomas-guettler.de
Mon Jul 11 09:47:04 EDT 2005


Am Sat, 09 Jul 2005 20:30:04 -0700 schrieb spike grobstein:

> I'm a total Python newbie, so bear with me here...
> 
> I'm writing a program that has a user-configurable, module-based
> architecture. it's got a directory where modules are stored (.py files)
> which subclass one of several master classes.
[cut]

> for item in dir_list:
>         # strip off the extensions...
>         if (item == "__init__.py"):
>                 continue
>         elif (item[-3:] == '.py'):

item.endswith(".py") would be more python-like.

>                 mod_name = item[:-3]
>         elif (item[-4:] == '.pyc'):

elif item.endswith(".pyc"):
    continue # Don't load module twice

>         else:
>                 continue
> 
>         print "Loading %s..." % mod
> 
>         module_list.append(__import__("Modules.%s" % mod))
> 
> print "Done."
> 
> 
> it works more or less like I expect, except that...
> 
> A. the first time it runs, blah.py then has a blah.pyc counterpart.
> When I run the program again, it imports it twice. Not horrible, but
> not what I want. is there any way around this?

See above: Just don't load it. The compiled "pyc" file is taken
automatically if it is newer than the "py" file.
 
> B. module_list winds up consisting of items called 'Modules.blah' and
> I'd like to have just blah. I realize I could say:
> 
> my_module = __import__("Modules.%s" % mod)
> module_list.append(getattr(my_module, mod))

I use this getattr() after __import__, too. I don't think there
is a easier way.

HTH,
  Thomas


-- 
Thomas Güttler, http://www.thomas-guettler.de/





More information about the Python-list mailing list