python 从同一文件夹导入 __import__ 失败

3 投票
1 回答
2205 浏览
提问于 2025-04-16 08:49

我有一个这样的目录结构:

|- 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]) 这一行。尽管 __init__.py 和 base.py 等文件都在同一个文件夹里,我已经确认这些模块文件里没有任何东西需要 __init__.py 中的内容,所以我真的不知道该怎么办。

1 个回答

2

你只需要把模块添加到系统路径中。请在你的 path = ... 这一行后面加上

import sys
sys.path.append(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()

撰写回答