从源导入时处理绝对导入时找不到父模块
我有以下的文件夹结构:
app/
ext/
gredis/
gredis.py
我有一个完整的路径指向 /Users/blah/blah/blah/ext/gredis/gredis.py
这个文件。
但是,当我尝试用下面的方式导入 ext.gredis.gredis
模块时:
imp.load_source('ext.gredis.gredis', path)
我遇到了以下错误:
RuntimeWarning: Parent module 'ext.gredis' not found while handling absolute import
我需要先导入 ext.gredis
吗?
注意:所有文件夹里都有一个 __init__.py
文件。
2 个回答
1
我发现的解决办法是确保传给 imp.load_source 的第一个参数(也就是你模块的名字)里没有句号。为什么这样做很重要我也不太清楚,但希望能帮到某个人。
3
你能把导致错误的代码发出来吗?这个对我来说是可以运行的:
$ tree
.
+-- app
¦ +-- test.py
+-- ext
¦ +-- gredis
¦ ¦ +-- gredis.py
¦ ¦ +-- gredis.pyc
¦ +-- test.py
+-- test.py
$ for path in test.py app/test.py ext/test.py; do python $path; done;
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
而test.py文件里面包含:
import imp
print(imp.load_source('ext.gredis.gredis', '/tmp/bla/ext/gredis/gredis.py'))
这个在python 2.x和3.x版本中都能正常工作。