i have directory structure so:
  |- project   |- commands.py   |- modules   | |- __init__.py   | |- base.py   | \- build.py   \- etc.... 
  i have following code in __init__.py
  commands = [] hooks = []  def load_modules():     """ dynamically loads commands /modules subdirectory """     path = "\\".join(os.path.abspath(__file__).split("\\")[:-1])     modules = [f f in os.listdir(path) if f.endswith(".py") , f != "__init__.py"]     print modules     file in modules:         try:             module = __import__(file.split(".")[0])             print module             obj_name in dir(module):                 try:                     potential_class = getattr(module, obj_name)                     if isinstance(potential_class, command):                         #init command instance , place in list                         commands.append(potential_class(serverprops))                     if isinstance(potential_class, hook):                         hooks.append(potential_class(serverprops))                 except:                     pass         except importerror e:             print "!! not load %s: %s" % (file, e)     print commands     print hooks 
  i'm trying __init__.py load appropriate commands , hooks lists given, hit importerror @ module = __import__(file.split(".")[0]) though __init__.py , base.py etc in same folder. have verified nothing in of module files requires in __init__.py, i'm @ loss of do.
        
  all you're missing having modules on system path. add
  import sys sys.path.append(path) 
  after path = ... line , should set. here's test script:
  import os, os.path, sys  print '\n'.join(sys.path) + '\n' * 3  commands = [] hooks = []  def load_modules():     """ dynamically loads commands /modules subdirectory """     path = os.path.dirname(os.path.abspath(__file__))      print "in path:", path in sys.path     sys.path.append(path)      modules = [f f in os.listdir(path) if f.endswith(".py") , f != "__init__.py"]     print modules     file in modules:         try:             modname = file.split(".")[0]             module = __import__(modname)             obj_name in dir(module):                 print '%s.%s' % (modname, obj_name )         except importerror e:             print "!! not load %s: %s" % (file, e)     print commands   load_modules() 
       
   
Comments
Post a Comment