Python 3 : 从顶级包导入模块
Python 3 : import module from top level package
我有一个简单的包结构,其中包含一个名为 ui
:
的模块
test/
├── app.py
├── __init__.py
└── ui
├── __init__.py
└── window.py
1 directory, 4 files
window.py
文件包含基本的 class :
# 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
调用 运行 函数,例如这个(我在包的父目录下):
>>> 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 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 中的相对导入方式
我有一个简单的包结构,其中包含一个名为 ui
:
test/
├── app.py
├── __init__.py
└── ui
├── __init__.py
└── window.py
1 directory, 4 files
window.py
文件包含基本的 class :
# 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
调用 运行 函数,例如这个(我在包的父目录下):
>>> 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 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 中的相对导入方式