2010-12-21 7 views
3

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.

+0

'__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. –

+0

'path = os.path.dirname (os.path.abspath (__ Datei __))' (korrekter und zufällig plattformübergreifend) –

+0

Woher und wie wird 'load_modules()' aufgerufen? – martineau

Antwort

2

Alles, was Sie verpassen, ist Module auf dem Systempfad. In

import sys 
sys.path.append(path) 

nach Ihrer path = ... Linie und Sie sollten eingestellt werden. Hier ist mein Testskript:

import os, os.path, sys 

print '\n'.join(sys.path) + '\n' * 3 

commands = [] 
hooks = [] 

def load_modules(): 
    """ dynamically loads commands from the /modules subdirectory """ 
    path = os.path.dirname(os.path.abspath(__file__)) 

    print "In path:", path in sys.path 
    sys.path.append(path) 

    modules = [f for f in os.listdir(path) if f.endswith(".py") and f != "__init__.py"] 
    print modules 
    for file in modules: 
     try: 
      modname = file.split(".")[0] 
      module = __import__(modname) 
      for obj_name in dir(module): 
       print '%s.%s' % (modname, obj_name) 
     except ImportError as e: 
      print "!! Could not load %s: %s" % (file, e) 
    print commands 


load_modules() 
Verwandte Themen