【发布时间】: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.py。from test import command有效吗?__import__('test').__file__是否指向您的test.py?
标签: python python-3.x python-import python-module python-importlib