【问题标题】:Importing modules from a "sub-sub-directory" in Python 3从 Python 3 中的“子子目录”导入模块
【发布时间】:2017-03-18 04:47:01
【问题描述】:

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

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

主目录中的__init__.py 包含命令import testsubdirtestsubdir 中的__init__.py 包含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 中进行这项工作的最佳方法是什么?

【问题讨论】:

    标签: python python-2.7 python-3.x


    【解决方案1】:

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

    在顶级__init__.py:

    from . import testsubdir
    

    testsubdir/__init__.py:

    from . import testsubsubdir
    

    【讨论】:

    • 这对你有用吗?我得到ValueError: Attempted relative import in a non-package 的行from . import testsubdir
    • @KurtPeek 我通过将顶级__init__.py 放入包testdir 并执行import testdir 进行了测试。
    • @KurtPeek 如果您想直接将顶级__init__.py 提供给python3,则将import 语句保留为import testsubdir
    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多