python - 从源导入会导致在处理绝对导入时找不到父模块

标签 python

我有以下文件夹结构;

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/

相关文章:

python - 如何用Python调用这个ATM机器游戏中的父类(super class)?

python - 对话框中的用户输入

python - 如何为具有清晰时间戳的时间序列数据构建数据框?

python - 如何优化我的代码以运行大值

python - Django 后端设计建议

Python 和缩进,入门难。

python - 为什么我得到 'ValueError: NaTType does not support strftime',即使它不为空?

javascript - Django serializeArray() 来自一个表单标签内的 2 个 django.form 字段

python - 如何将/proc/net/dev 的输出解析为 key :value pairs per interface using Python?

检查特定 Linux 命令是否仍在运行的 Python 脚本