【问题标题】:python __import__ from same folder fails来自同一文件夹的 python __import__ 失败
【发布时间】:2010-12-21 04:00:42
【问题描述】:

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

|- 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 中的任何内容,所以我真的不知道该怎么办。

【问题讨论】:

  • __import__ 有很多需要注意的细节,尤其是与 fromlist 相关的部分。试着搜索一下,看看你能不能弄明白。
  • path = os.path.dirname(os.path.abspath(__file__))(更正确,顺便说一句跨平台)
  • 从哪里以及如何调用load_modules()
  • load_modules 在初始化期间从 commands.py 调用

标签: python import importerror


【解决方案1】:

您所缺少的只是在系统路径上有模块。添加

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

【讨论】:

    猜你喜欢
    • 2012-04-28
    • 2012-01-27
    • 1970-01-01
    • 2012-05-25
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多