我有以下文件夹结构;
app/
ext/
gredis/
gredis.py
我在 /Users/blah/blah/blah/ext/gredis/gredis.py
中有 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
最佳答案
您可以发布重现该错误的代码吗?这对我有用:
$ 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。
关于python - 从源导入会导致在处理绝对导入时找不到父模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612358/