ich eine Verzeichnisstruktur wie so haben:Python __import__ aus demselben Ordner nicht
|- project
|- commands.py
|- Modules
| |- __init__.py
| |- base.py
| \- build.py
\- etc....
Ich habe den folgenden Code in __init__.py
commands = []
hooks = []
def load_modules():
""" dynamically loads commands from the /modules subdirectory """
path = "\\".join(os.path.abspath(__file__).split("\\")[:-1])
modules = [f for f in os.listdir(path) if f.endswith(".py") and f != "__init__.py"]
print modules
for file in modules:
try:
module = __import__(file.split(".")[0])
print module
for obj_name in dir(module):
try:
potential_class = getattr(module, obj_name)
if isinstance(potential_class, Command):
#init command instance and place in list
commands.append(potential_class(serverprops))
if isinstance(potential_class, Hook):
hooks.append(potential_class(serverprops))
except:
pass
except ImportError as e:
print "!! Could not load %s: %s" % (file, e)
print commands
print hooks
Ich versuche __init__.py
zu bekommen die entsprechenden Befehle zu laden und Haken in die Listen gegeben, aber ich traf immer einen ImportError um , obwohl __init__.py
und base.py usw. alle im selben Ordner sind. Ich habe überprüft, dass nichts in irgendeiner der Moduldateien irgendetwas in __init__.py
erfordert, also bin ich wirklich ratlos was zu tun ist.
'__import__' hat ziemlich viele fiddly Bits müssen Sie bewusst sein, vor allem mit' fromlist' zu tun. Versuchen Sie, danach zu suchen und zu sehen, wenn Sie es herausfinden können. –
'path = os.path.dirname (os.path.abspath (__ Datei __))' (korrekter und zufällig plattformübergreifend) –
Woher und wie wird 'load_modules()' aufgerufen? – martineau