我的包裹结构:
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路径:
那么为什么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'