Ich möchte Module die ich in einem Verzeichnis "Plugins" ablege beim Start meines Turbogears-Servers automatisch importieren. Ich habe jedoch das Problem, dass die importierten Module nicht ihre richtigen Namen haben. Ich habe mir eine Testdatei geschrieben die wie folgt aussieht:
Code: Alles auswählen
import os
import sets
import imp
def find_modules(path="./plugins"):
"""Return names of modules in a directory.
Returns module names in a list. Filenames that end in ".py" or
".pyc" are considered to be modules. The extension is not included
in the returned list.
"""
modules = sets.Set()
for filename in os.listdir(path):
module = None
if filename.endswith(".py"):
module = filename[:-3]
elif filename.endswith(".pyc"):
module = filename[:-4]
if module is not None:
modules.add(module)
print modules
return list(modules)
def load_module(name, path=["./plugins"]):
"""Return a named module found in a given path."""
(file, pathname, description) = imp.find_module(name, path)
return imp.load_module(name, file, pathname, description)
def functions_in_module(module):
functions = []
for obj in module.__dict__.values():
if isinstance(obj, types.FunctionType):
functions.append(obj)
print functions
return functions
for name in find_modules():
print 'importing: '+ name
temp=load_module(name) #this should be mplug
temp.testor() #testfunction, should be mplug.testor()
print temp.bladic #tempdict in testfunction, should be mplug.bladic
in der letzten for-Anweisung werden alle alle Dateien in dem Verzeichnis die in Frage kommen zurückgegeben und pro Eintrag load_module aufgerufen. Meine Testdatei heißt mplug.py und so möchte ich sie später auch ansprechen können mit z.b. mplug.testfunction(). Ich habe deshalb in der Schleife temp vergeben und das Modul anprechen zu können, temp soll jedoch nicht temp heißen, sondern so wie das modul das ich importiere. Habt ihr dazu eine Idee?