我正在使用 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
请您参考如下方法:
提示。通过修改 sys.path 找到了一个临时解决方法,尽管我不喜欢它。似乎应该有一种方法可以在不弄乱 sys.path 的情况下执行此操作。我 try catch ImportError 但它只包含一个字符串而不是试图导入的模块的名称(是的,我可以解析该字符串,但这是完全错误的)
a/foo.py:
import imp
import sys
def find_and_load(module, path):
file, pathname, description = imp.find_module(module, path)
try:
n = len(sys.path)
sys.path += path
return imp.load_module(module, file, pathname, description)
finally:
del sys.path[n:]
file.close()
m = find_and_load('bar',['../b'])
print m.tweedledee() + m.tweedledum()
b/bar.py:
import baz
def tweedledee():
return 42
tweedledum = baz.tweedledum
