【发布时间】:2015-06-17 21:50:15
【问题描述】:
我正在使用imp 模块来动态导入 Python 模块。效果很好。
但是我的一位同事想将一些模块重构到同一目录中的另一个模块中,这会破坏事情。我怎样才能让它工作?我将正确的路径传递给find_module;对bar 的动态导入工作正常,但是当bar 尝试从同一目录中拉入baz 时,它会失败。源代码转载于下方和github。
C:\tmp\git\python-imp-bug>cd a
C:\tmp\git\python-imp-bug\a>python foo.py
Traceback (most recent call last):
File "foo.py", line 7, in <module>
m = find_and_load('bar',['../b'])
File "foo.py", line 5, in find_and_load
return imp.load_module(module, file, pathname, description)
File "../b\bar.py", line 1, in <module>
import baz
ImportError: No module named baz
a/foo.py:
import imp
def find_and_load(module, path):
file, pathname, description = imp.find_module(module, path)
return imp.load_module(module, file, pathname, description)
m = find_and_load('bar',['../b'])
b/bar.py:
import baz
def tweedledee():
return 42
b/baz.py:
def tweedledum():
return 24
【问题讨论】:
-
换句话说:
imp.load_module()怎么不带路径参数?