为什么Pycharm无法使用相对导入来运行代码?

时间:2018-08-27 10:38:47

标签: python python-3.x pycharm python-import relative-import

我的包裹结构:

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'

1 个答案:

答案 0 :(得分:1)

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

enter image description here

打印sys.path表示PyCharm在此处添加了绝对路径到root_pkg,而它没有添加内容根目录的子文件夹。令我感到困惑的是,它解决了相对进口权,而绝对进口权却出现了错误,而两者在运行时都无法解决。