2010-12-21 180 views
3

我有一個目錄結構如下所示:蟒蛇__import__失敗

|- project 
    |- commands.py 
    |- Modules 
    | |- __init__.py 
    | |- base.py 
    | \- build.py 
    \- etc.... 

我在__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 

下面的代碼,我試圖讓__init__.py加載相應的命令並鉤入列表中,但我總是在module = __import__(file.split(".")[0])處遇到ImportError,儘管__init__.py和base.py等都在同一個文件夾中。我已驗證任何模塊文件中沒有任何內容需要__init__.py中的任何內容,所以我真的不知道該怎麼做。

+0

'__import__'有很多需要注意的煩人的部分,特別是''fromlist'。試着搜索一下,看看你能否弄清楚。 – 2010-12-21 04:05:25

+0

'path = os.path.dirname(os.path.abspath(__ file __))'(更正確,偶然跨平臺) – 2010-12-21 04:09:37

+0

load_modules()從哪裏調用? – martineau 2010-12-21 08:40:08

回答

2

所有你缺少的是在系統路徑上有模塊。添加

import sys 
sys.path.append(path) 

在您的path = ...行之後,您應該設置。這裏是我的測試腳本:

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()