pycharm import工程内其他目录包错误问题

1.问题1

我的工程目录结构如下:

test
    -src
        -common
            -__init__.py
            -Logger.py
        -core
            -test.py

我在test.py里面导入Logger.py里面的类。

from ..common.Logger import LOG

if __name__ == "__main__":
    LOG.debug("this is log test")

执行时报错:

Traceback (most recent call last):
  File "C:/test/src/db/Connecter.py", line 12, in
    from ..common.Logger import LOG
ValueError: attempted relative import beyond top-level package

通过百度找到下面的解决方案:

import sys
sys.path.append("../common/")

from Logger import LOG

if __name__ == "__main__":
    LOG.debug("this is log test")

执行代码成功,但是还有下面问题。

2.问题2

上面代码虽然执行成功,但是我使用的PyCharm ide页面报错

pycharm import工程内其他目录包错误问题_第1张图片

this inspection detects names that should resolve but don't.due to dynamic dispatch and duck typing,this is possible in a limited but useful number of cases .top-level and class-level items are supported better than instance items

继续百度,在PyCharm的setting中有Project Structure设置,ide自动把跟目录设置为source,这样import的模块类等,就是通过这些source文件夹作为根路径来查找,也就是说在这些source文件夹中查找import的东西。

from src.common.Logger import LOG 

if __name__ == "__main__":
    LOG.debug("this is log test")

这样修改,页面没有报错信息,并且执行成功。

你可能感兴趣的:(python)