简体   繁体   中英

Pylint "unable to import" error but works fine with Pycharm

The basic structure of my program looks like this:

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

In Pycharm all imports just work fine. For example I use the following import in 'module_with_import.py':

from sub_dir.sub_sub_dir.example_module import function

However if I run pylint on module_with_import.py I will get the following error:

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

Does anybody see what's wrong here?

Module (package) cannot have minus in name. Rename Sub-dir to sub_dir , Sub-sub-dir to sub_sub_dir and Sub-sub-dir2 to sub_sub_dir2 .

Next read PEP-8 The Python Style Guide

Are top_dir and sub_dir named the same thing? If so, and there are no files to import in the top_dir (just modules housed in that directory), delete the __init__.py & __init__.pyc files and try again.

Imagine the following case:

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

If your import statement is something like import foo.bar.baz or from foo.bar import baz and you're running your script from the top level 'foo', importing will fail because python importing places the current directory in sys.path . You either need to tell python that the top level is not a module, or you need to insert the path you want into sys.path.

I resolve the issue by doing the following:

  1. Go to your base project
  2. Create a.pylintrc file inside your base project
  3. Add the following content to.pylintrc file
[MASTER]
init-hook='import sys; sys.path.append("/path/to/virtualenv_or_pipenv/.../Lib/site-packages/")'

You can check the Pycharm project settings/preference for the Python Interpreter paths. The Interpreter is Scripts (in case of Windows system), use the Lib folder path instead(/path_to/.../Lib/site-packages/)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM