Pylint“无法导入”错误,但可以与Pycharm配合使用

2024-04-19 14:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序的基本结构如下:

top_dir
__init__.py
readme.rst
    sub_dir
    __init__.py
        sub_sub_dir
        __init__.py
        example_module.py
        sub_sub_dir2
        __init__.py
        module_with_import.py

在皮查姆,所有的进口商品都很好用。例如,我在'module_with_import.py'中使用以下导入:

from sub_dir.sub_sub_dir.example_module import function

但是,如果我使用import.py在module_上运行pylint,将得到以下错误:

Unable to import 'sub_dir.sub_sub_dir.example_module' (import-error)

有人看到这里出了什么事吗?


Tags: frompyimport程序initexampletopdir
2条回答

模块(包)名称中不能有减号。将Sub-dir重命名为sub_dir,将Sub-sub-dir重命名为sub_sub_dir,将Sub-sub-dir2重命名为sub_sub_dir2

下一次阅读PEP-8 The Python Style Guide

top_dir和sub_dir是同一个名字吗?如果是,并且在顶层目录中没有要导入的文件(只是该目录中包含的模块),请删除__init__.py&;__init__.pyc文件并重试。

想象一下下面的情况:

foo
__init__.py
  foo
  __init__.py
     bar
     __init__.py
     baz.py

如果您的import语句类似于import foo.bar.bazfrom foo.bar import baz,并且您正在从顶级“foo”运行脚本,则导入将失败because python importing places the current directory in sys.path。您要么需要告诉python顶层不是模块,要么需要将所需的路径插入sys.path。

相关问题 更多 >