【问题标题】:__import__: can't find class [closed]__import__:找不到类[关闭]
【发布时间】:2021-02-14 23:19:03
【问题描述】:

我希望我的代码从路径导入所有模块并允许用户访问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 没有任何效果。请帮我解决这个问题。

【问题讨论】:

  • 我想问一下你想用这些hackery实现什么功能?
  • 这是大代码的一部分。这个函数应该导入模块并将它的类保存到dict。在此用户将能够从 dict 执行模块。
  • from test import command ?
  • 不!我需要从路径 test1 test2 test3 testN 导入所有模块。 import_modules() 从路径中导入所有模块,不仅测试!
  • 此设置对导入路径敏感。你怎么称呼import_modules?请注意,有一个标准库 test 模块可能会影响您的 test.pyfrom test import command 有效吗? __import__('test').__file__ 是否指向您的 test.py

标签: python python-3.x python-import python-module python-importlib


【解决方案1】:

你没有提供你是如何使用 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? 的副本

【讨论】:

  • 不!这不是我问的问题,我问为什么__import__ 在模块中找不到类命令!
  • 不能,因为您正在导入不同的模块。尝试检查您导入的模块的 m.__path__ 是否是您尝试导入的模块。
  • 问题可能是sys.path.append(path) - 将新的搜索路径放在末尾​​i>。标准库路径肯定在最后。
  • 好的。你能解释一下为什么这在这个项目中有效吗:github.com/neoneggplant/EggShell/blob/…
  • 我不知道它在那里是否有效。甚至该代码在该项目中应该做什么。附带说明:尝试将 test.py 更改为不太通用的内容,例如 test_me.py
猜你喜欢
  • 2010-11-13
  • 2017-11-25
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
相关资源
最近更新 更多