来自同一文件夹的 python __import__ 失败
我有一个像这样的目录结构:
|- 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
中的任何内容,因此我真的不知道该怎么做。
I have a directory structure like so:
|- project
|- commands.py
|- Modules
| |- __init__.py
| |- base.py
| \- build.py
\- etc....
I have the following code in __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
I'm trying to get __init__.py
to load the appropriate commands and hooks into the lists given, however i always hit an ImportError at module = __import__(file.split(".")[0])
even though __init__.py
and base.py etc are all in the same folder. i have verified that nothing in any of the module files requires anything in __init__.py
, so i'm really at a loss of what to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所缺少的只是系统路径上的模块。 添加
在
path = ...
行之后 ,您应该已设置完毕。这是我的测试脚本:All you're missing is having Modules on the system path. Add
after your
path = ...
line and you should be set. Here's my test script: