ich habe folgendes Problem:
Ich möchte ein Modul das eine Klasse enthält dynamisch zur Laufzeit importieren und die Klasse verwenden.
Der Name der Klasse und des Moduls sind Identisch, nur die Klasse ist uppercase.
Beispiel:
Code: Alles auswählen
tool.py install
Code: Alles auswählen
tool.py remove
usw...
So weit alles ok, allerdings habe ich ein Problem mit den Namensräumen.
Ich habe mir eine Klasse TOOL gebaut, welche zwei private Funktionen hat: __load_modules() und __call_module()
Mein Problem ist nun, dass ich nach dem Aufruf von
Code: Alles auswählen
from install import *
Hier sind die zwei Funktionen von meiner TOOL Klasse:
Code: Alles auswählen
#=============================================================================
# module loader
#=============================================================================
def __module_loader(self):
print ">> Start: module loader"
# Read the contents of the module directory
modules = []
for module_file in os.listdir("./modules"):
if re.search(".pyc", module_file):
continue
modules.append( { "name": module_file.strip(".py"),
"file": module_file
} )
# Import all modules
sys.path.append("./modules")
for module in modules:
print ">>> Importing module '"+ module["name"] + "'\t from file '" + module["file"] + "'..."
importstring = "from install import *"
print importstring
exec importstring
INSTALL() # <-- Das ist erfolgreich
print ">> Ended: module loader"
#=============================================================================
# module caller
#=============================================================================
def __module_caller(self):
print ">> Start: module caller"
INSTALL() # <- Das ist nicht erfolgreich
# classname = "INSTALL"
# print ">>> Calling class '" + classname + "'..."
# eval(classname)()
print ">> Start: module caller"
Code: Alles auswählen
>> Start: module loader
>>> Importing module 'install' from file 'install.py'...
from install import *
>>>> install.py imported.
>>> Start: Install constructor
>>> Ended: Install constructor
>> Ended: module loader
>> Start: module caller
Traceback (most recent call last):
File "./tool.py", line 77, in <module>
TEST()
File "./tool.py", line 70, in __init__
self.__module_caller()
File "./tool.py", line 57, in __module_caller
INSTALL()
NameError: global name 'INSTALL' is not defined
Ich dachte bisher immer, wenn ich etwas mit from x import * importiere, ist es dann global verfügbar.
Ist es aber anscheinend nicht. Wie mache ich es dann global verfügbar?
Danke
Daniel