[英]python importlib imports from wrong directory
I am trying to import dicts named 'tasks' from different python files (*.py).我正在尝试从不同的 python 文件 (*.py) 中导入名为“tasks”的字典。
The paths are stored in my array directories['code']
.路径存储在我的数组
directories['code']
。 Not all files contain one of these tasks dicts.并非所有文件都包含这些任务字典之一。
The problem is, once a file with a dict was found, 'foo' will be set to that dict, but won't be reset , even if the next file does not have a dict.问题是,一旦找到带有 dict 的文件,'foo' 将被设置为该 dict,但不会被 reset ,即使下一个文件没有 dict。
However, 'foo' will be assigned correctly again, once another file was found containing a new dict.但是,一旦发现另一个包含新字典的文件,'foo' 将再次被正确分配。
I wonder if this is because importlib
is searching an entire tree, not just the exact path?我想知道这是不是因为
importlib
正在搜索整个树,而不仅仅是确切的路径?
And of course, how can I fix this?当然,我该如何解决这个问题?
import importlib
for i in range(len(directories['code'])):
try:
foo = importlib.machinery.SourceFileLoader('file', directories['code'][i]).load_module().tasks
except:
foo = '0'
pass
print(foo)
Your code is valid, there is one place where is something goes wrong -- directories['code'][i]
, -- so try to use i
:你的代码是有效的,有一个地方出了问题——
directories['code'][i]
,——所以尝试使用i
:
for i in ['test/__init__.py', 'test/__init__2.py']:
try:
foo = importlib.machinery.SourceFileLoader('file', i).load_module().__version__
except:
foo = 0
print(i, foo)
# test/__init__.py 1.0.0
# test/__init__2.py 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.