importing / loading a module / class dynamically

Laszlo Nagy gandalf at designaproduct.biz
Fri Jan 5 11:40:45 EST 2007


> .../.../../plugin/name1/name1.py
> ....
> .../.../../plugin/namen/namen.py
>
>
> I block at the beginning and tried this (test.py is a real file)
>   
>>>> s = 'test.py'
>>>> eval ('import ' + s)
>>>>         
import test.py  # This is invalid
import test # This MAY be valid
import name1.name1 # Most probably this is what you want if you have the 
aforementioned directory stucture
from name1 import name1 # Or this?

You must also:

1. Have the 'plugin' dir in your sys.path
2. Have at least an empty plugin/name1/__init__.py file

Another alternative is to have plugins/__init__.py and do something like:

from plugins.name1 import name1

You should not overcomplicate things anyway. If you do not need these 
name1...namen directories for sure, then just drop them.

Hint: try this (untested)

import os
fnames = os.listdir('plugins')
for fname in fnames:
    if os.path.isdir(fname):
       root,ext = os.path.splitext(fname)
       cmd = "from plugins.%s import %s" % (root,root)
       print "I should eval this:",cmd

Best,

   Laszlo


> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in -toplevel-
>     eval ('import ' + s)
>   File "<string>", line 1
>     import test.py
>   




More information about the Python-list mailing list