__import__:找不到课程

问题描述

我希望我的代码从路径导入所有模块并允许用户访问command类,但是在尝试导入类command之后,__import__无法做到这一点。

core.py:

def import_modules(path):
    modules = dict()
    for mod in os.listdir(path):
        if mod == '__init__.py' or mod[-3:] != '.py':
            continue
        else:
            m = __import__(mod[:-3]).command() # error here
            modules[m.name] = m
    return modules

commands = import_modules('test_directory/tests')
commands["test"].run()

test.py:

class command:
    def __init__(self):
        self.name = "test"
        self.description = "test"
        self.usage = "Usage: test"
        self.args = 1

    def run(self):
        print("test")

错误

AttributeError: module 'test' has no attribute 'command'

我真的需要帮助。

我通过import lib进行了尝试,通过getattr进行了任何操作。请帮我解决这个问题。

解决方法

您尚未提供您使用import_modules的确切方式,但是 最有可能导致您最终导入https://docs.python.org/3/library/test.html此模块。

我怀疑,您正在将诸如“ test.py”之类的内容传递给import_modules,它最终像在sys.path上那样。这不是sys path的工作方式-应该是目​​录列表,请参见https://docs.python.org/3/library/sys.html#sys.path

这看起来像是How to load all modules in a folder?的副本