我在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'

我怎么解决这个问题?


当前回答

I have been struggling with this a lot and eventually found out something that was not described here. Here are my 2 cents to this issue: I am using VS Code on Windows, using virtual env. For some reasons, the pylint executable is called epylint and not pylint. In my script or from CLI prompt, I was running pylint ./xxx and the system was launching a pylint it found somewhere else but not the appropriate one. I just added an e in my shell script and my 'Unable to import' issues eventually vanished.

其他回答

我知道有两个选择。

第一,更改PYTHONPATH环境变量以包括模块上面的目录。

或者,编辑~/。Pylintrc来包含你的模块上面的目录,像这样:

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

(或者在其他版本的pylint中,init-hook要求你将[General]更改为[MASTER])

这两种选择都应该有效。

也许通过手动在PYTHONPATH中追加目录?

sys.path.append(dirname)

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

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

它在PyCharm IDE中为我工作

这些都对我有用!

.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])'

如果你使用的是Windows:

获取刚刚创建的虚拟环境中python.exe的路径 它应该像这样Z:\YourProjectFolder\Scripts\python.exe 然后转到vscode,编辑user settings.json 添加这一行:"python。pythonPath环境”:“Z: \ \ YourProjectFolder \ \ \ \ python.exe脚本” 保存它,这应该可以解决问题 注意:在json文件中使用双反斜杠而不是单反斜杠

{
    "python.pythonPath": "Z:\\YourProjectFolder\\Scripts\\python.exe"
}