【问题标题】:Python 3 : import module from top level packagePython 3:从顶级包导入模块
【发布时间】:2021-02-05 10:42:57
【问题描述】:

我有一个简单的包结构,其中包含一个名为 ui 的模块:

test/
├── app.py
├── __init__.py
└── ui
    ├── __init__.py
    └── window.py

1 directory, 4 files

window.py 文件包含一个基本类:

# test/ui/window.py

class Window():
    def __init__(self):
        print("Window constructor")

在我的app.py 我有:

# test/app.py

from ui import window

def run():
    w = window.Window()

现在在 Python 3 shell 中,我应该可以从包 test 中导入模块 app,像这样调用 run 函数(我在包的父目录中):

>>> import test.app
>>> test.app.run()

但是我得到了这个错误(使用 Python3):

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/app.py", line 1, in <module>
    from ui import window
ModuleNotFoundError: No module named 'ui'

请注意,这适用于 Python2.7...

这里有什么问题?

【问题讨论】:

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


    【解决方案1】:

    在 python 3.8 中测试

    # test/app.py
    
    from .ui import window
    
    
    def run():
        w = window.Window()
    
    >>> import test.app
    >>> test.app.run()
    Window constructor
    

    你必须制作一个 .在 ui 前面说您正在使用本地文件夹。 由于我一般对 python 2 了解不多,我无法向你解释它为什么在那里工作,但我最好的猜测是,他们改变了如何在 python 3 中进行相对导入

    【讨论】:

    • 谢谢,它适用于 python 2.7 和 python 3.8 实际上具有相对导入。
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 2012-12-24
    • 2016-07-30
    • 2020-08-27
    • 2018-10-27
    • 2011-05-04
    相关资源
    最近更新 更多