python - 在 Python 3 中从 "sub-sub-directory"导入模块

标签 python python-2.7 python-3.x

我有一个如下所示的目录树(使用 tree 进行可视化):

.
├── __init__.py
└── testsubdir
    ├── __init__.py
    └── testsubsubdir
        ├── __init__.py
        └── __init__.pyc

主目录中的__init__.py包含命令import testsubdir,以及testsubdir中的__init__.py code> 包含 import testsubsubdir。我注意到这在 Python 2.7 中有效,但在 Python 3.5 中无效:

kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python __init__.py
kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python3 __init__.py
Traceback (most recent call last):
  File "__init__.py", line 1, in <module>
    import testsubdir
  File "/home/kurt/Documents/Scratch/testdir/testsubdir/__init__.py", line 1, in <module>
    import testsubsubdir
ImportError: No module named 'testsubsubdir'

我正在努力将一些源代码从 Python 2“翻译”为 Python 3,其中包含与上面类似的导入语句。在 Python 3 中实现此功能的最佳方法是什么?

最佳答案

This answer to a similar question建议使用相对导入:

在顶层__init__.py:

from . import testsubdir

testsubdir/__init__.py中:

from . import testsubsubdir

关于python - 在 Python 3 中从 "sub-sub-directory"导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421179/

相关文章:

python - Pandas 按组将列转换为多个

Python、嵌套循环、匹配和性能

Python doctest 异常

python - OpenCV TypeError : contour is not a numpy array, 既不是标量

python - 返回日期时间 DataFrame 中每天唯一列条目的计数

python - 当你从列表中删除一个项目时,为什么内存大小没有改变?

regex -\b 与 Regex/Python 的行为不符预期

python - 加快动画 gif kivy 的加载

python - 如何将 pyspark.sql.dataframe.DataFrame 转换回 databricks notebook 中的 sql 表

python - 来自 Python 生成器的 Google Cloud Storage 流式上传