我在Windows上的Wing IDE内部运行PyLint。我有一个子目录(包)在我的项目和包内,我从顶层导入一个模块,即。

__init__.py
myapp.py
one.py
subdir\
    __init__.py
    two.py

在two.py中,我导入了一个,这在运行时工作得很好,因为顶层目录(myapp.py从其中运行)在Python路径中。然而,当我在two.py上运行PyLint时,它会给我一个错误:

F0401: Unable to import 'one'

我怎么解决这个问题?


当前回答

把另一个可能的答案扔到堆里。我尝试了这里提供的许多解决方案。要么是我做错了,要么是我的pylint导入错误是由其他原因引起的。不管怎样,我的解决方法非常简单。

解决方案:重新安装包含您无法导入的所有模块的包(PyPi包而不是pip包),然后重新安装pylint,以便pylint和这些模块由相同的pip安装。

对我来说,拥有正确的目录并不管用。我从另一个关于他的问题的帖子中得到了这个想法。

其他回答

安装Python时,可以设置路径。如果path已经定义了,那么你可以在VS Code中,按Ctrl+Shift+P,输入Python:选择解释器,然后选择Python的更新版本。点击此链接获取更多信息,https://code.visualstudio.com/docs/python/environments

在这两个目录中都有一个空的__init__.py文件来让python知道dirs是模块吗?

当你不是从文件夹中运行时(比如可能从pylint的文件夹中运行,尽管我没有用过),基本的大纲是:

topdir\
  __init__.py
  functions_etc.py
  subdir\
    __init__.py
    other_functions.py

这就是python解释器如何在不引用当前目录的情况下感知模块,因此如果pylint从它自己的绝对路径运行,它将能够以topdir的身份访问functions_etc.py。Functions_etc或topdir.subdir。other_functions,前提是topdir在PYTHONPATH上。

UPDATE: If the problem is not the __init__.py file, maybe just try copying or moving your module to c:\Python26\Lib\site-packages -- that is a common place to put additional packages, and will definitely be on your pythonpath. If you know how to do Windows symbolic links or the equivalent (I don't!), you could do that instead. There are many more options here: http://docs.python.org/install/index.html, including the option of appending sys.path with the user-level directory of your development code, but in practice I usually just symbolically link my local development dir to site-packages - copying it over has the same effect.

在init-hook中改变路径的解决方案很好,但我不喜欢必须在那里添加绝对路径的事实,因此我不能在项目的开发人员之间共享这个pylintrc文件。这个解决方案使用相对路径pylintrc文件更适合我:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

请注意pylint.config.PYLINTRC也存在,并且具有与find_pylintrc()相同的值。

这些都对我有用!

.pylintrc

[MASTER]
; init-hook='import sys; sys.path.append("./venv/lib/python3.8/site-packages")'

; or
init-hook='import sys; sys.path.append(f"./venv/lib/python{sys.version[:3]}/site-packages");'

; or
;init-hook='from distutils.sysconfig import get_python_lib; sys.path.append(get_python_lib())'

; or
; init-hook='import site; sys.path.append(site.getsitepackages()[0])'

我在项目的根目录中添加了一个新文件pylintrc

[MASTER]
init-hook='import sys; sys.path.append(".")'

它在PyCharm IDE中为我工作