gpt4 book ai didi

python - 为什么 Pycharm 不能运行相对导入的代码?

转载 作者:行者123 更新时间:2023-12-01 22:05:55 25 4
gpt4 key购买 nike

我的包结构:

root_pkg
root_pkg/__init__.py # empty
root_pkg/game
root_pkg/game/__init__.py # empty
root_pkg/game/game1.py
root_pkg/utils
root_pkg/utils/__init__.py # empty
root_pkg/utils/lib.py

root_pkg/game/game1.py 包含:

"""File root_pkg/game/game1.py"""

from ..utils import lib

不会发出任何错误

但是在 pycharm 中运行:

C:\_\Python363-64\python.exe C:/Dropbox/eclipse_workspaces/python/test_imports/root_pkg/game/game1.py
Traceback (most recent call last):
File "C:/Dropbox/eclipse_workspaces/python/test_imports/root_pkg/game/game1.py", line 3, in <module>
from ..utils import lib
ValueError: attempted relative import beyond top-level package

Process finished with exit code 1

但是,内容和源路径被添加到运行配置中的python路径:

enter image description here

那么为什么 Pycharm 不能运行这个呢?它不应该将项目文件夹添加到 PYTHONPATH 吗?使用的导入样式是否正确?

编辑:将运行配置中的工作目录更改为 C:\Dropbox\eclipse_workspaces\python\test_imports\ 导致相同的错误:

C:\_\Python363-64\python.exe C:/Dropbox/eclipse_workspaces/python/test_imports/root_pkg/game/game1.py
Traceback (most recent call last):
File "C:/Dropbox/eclipse_workspaces/python/test_imports/root_pkg/game/game1.py", line 3, in <module>
from ..utils import lib
ValueError: attempted relative import beyond top-level package

请注意,它使用 -m 开关从命令行运行良好,因此 PyCharm 没有出错是正确的:

C:\Dropbox\eclipse_workspaces\python\test_imports>C:\_\Python363-64\python.exe -m root_pkg.game.game1

将其更改为绝对导入 from utils import lib 在 pycharm 中显示错误并且在命令行中也失败:

C:\Dropbox\eclipse_workspaces\python\test_imports>C:\_\Python363-64\python.exe root_pkg/game/game1.py
Traceback (most recent call last):
File "root_pkg/game/game1.py", line 3, in <module>
from utils import lib
ModuleNotFoundError: No module named 'utils'

C:\Dropbox\eclipse_workspaces\python\test_imports>C:\_\Python363-64\python.exe -m root_pkg.game.game1
Traceback (most recent call last):
File "C:\_\Python363-64\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\_\Python363-64\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Dropbox\eclipse_workspaces\python\test_imports\root_pkg\game\game1.py", line 3, in <module>
from utils import lib
ModuleNotFoundError: No module named 'utils'

最佳答案

root_pkg 添加到源文件夹使运行配置工作(并且 PyCharm 不会在绝对导入时出错)。

enter image description here

打印 sys.path 显示 PyCharm 添加了 root_pkg 的绝对路径,但它没有添加内容根目录的子文件夹。让我感到困惑的是,它解决了相对导入权,而它在绝对导入权上出错,而​​两者都无法在运行时解决。

关于python - 为什么 Pycharm 不能运行相对导入的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037480/

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