gpt4 book ai didi

Python3 子模块设置在使用 -m 开关运行时不更新路径

转载 作者:行者123 更新时间:2023-11-28 22:46:45 25 4
gpt4 key购买 nike

我有以下项目结构:

server/
server.py
__init__.py

sockets/
module.py
__init__.py

我将 PYTHONPATH 设置为服务器上方的一个目录(例如 /home/user/server 包含服务器,PYTHONPATH 设置为 /home/user).

主文件是server.py;它导入模块:

import sockets
from sockets.module import Module

当我直接运行 python3 $PYTHONPATH/server/server.py 时,它运行良好。然而,当我调用 python3 -m server.server.py 时,它失败了,尽管明确建议避免 Python 路径 hell ,但它找不到模块,并显示一条丑陋的消息:

/usr/bin/python3: Error while finding spec for 'server.server.py' (<class 'ImportError'>: No module named 'sockets')

为什么模块导入导入子模块失败?如何正确设置子包?

最佳答案

行为是完全正确的; sockets 不是顶级模块。但是,当您使用 $PYTHONPATH/server/server.py 时,Python 还会将 $PYTHONPATH/server/ 添加到 Python 搜索路径,所以现在 sockets 一个顶层模块。永远不要直接运行包中的文件。

相对于当前包导入套接字:

from . import sockets
from .sockets.module import Module

或使用完全合格的导入:

from server import sockets
from server.sockets.module import Module

另见 Interface Options section精美手册中的 Python 设置和使用部分:

If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

请注意,-m 开关采用 python 标识符,而不是文件名,因此请使用:

python -m server.server

离开 .py 扩展。

关于Python3 子模块设置在使用 -m 开关运行时不更新路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com