(False) 在 Visual Studio 代码中的虚拟环境中使用全局 PyLint 导入错误警告

(False) import error warning with global PyLint in virtual environment in Visual Studio Code

我在Python中使用Visual Studio代码进行编码。 在我的 python 文件中,我声明了以下导入:

import requests
from bs4 import BeautifulSoup

我创建了一个虚拟环境,在虚拟环境中使用 pip install 安装了所有必需的包,python 脚本运行正常。

在 Visual Studio 代码中,我修改了设置以使用安装在全局级别的 PyLint(意味着默认 python 解释器)所以我不需要在我的虚拟机中安装 pylint环境以避免它出现在我的 requirements.txt 中。我的 .vscode/settings.json 看起来像这样:

{
    "python.pythonPath": "/Users/pazifik/.virtualenvs/fun-image-scraper/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "/opt/homebrew/bin/pylint"
}

Visual Studio 代码似乎正确地获取了 Pylint,但是在“问题”视图中它显示了这个:

Unable to import 'requests' pylint(importError) [3, 1]
Unable to import 'bs4' pylint(importError) [4, 1]

原因可能是全局安装的PyLint看不到虚拟环境里面的包。在 Visual Studio 代码中选择的 Python 解释器是来自虚拟环境的 Python 解释器。

如何消除 Visual Studio 代码中的这些(错误的)导入错误?

编辑: 为了更好地可视化我的问题和设置,这里有一些屏幕截图:

pip虚拟环境安装包列表

pip show of requestspackage 在虚拟环境中

“问题”视图(但是!如前所述,脚本运行良好,只是那里显示的错误令人困惑,因此我的问题)

PyLint 安装在带有默认解释器的全局环境中

抱歉,它在我的电脑上运行良好。您能否再次确认选择了哪个 python 解释器,以及安装了 python 包的位置?

您可以从 VSCode 左下角或终端中的环境名称中获取您使用的 python 解释器:

settings.json中python.pythonPath的设置无法确定您使用的是哪个python解释器。

也许你只是在不同的环境下安装了包,你可以通过pip show {packagename}命令查看包安装到哪里了?

非常抱歉我之前的回答,我之前修改过pylintArgs,所以我没有发现问题。

您可以在 settings.json 中添加:

"python.envFile": "${workspaceFolder}/.env",

并在工作区文件夹下创建一个名为.env的文件,并在其中添加:

PYTHONPATH=/Users/pazifik/.virtualenvs/fun-image-scraper/lib/python3.9/site-packages

说明:

虽然在VSCode中选择了虚拟环境,可以发现在终端中修改了PYTHONPATH,但是pylint并没有通过终端路由, 所以它不会得到修改后的 PYTHONPATH.

When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.

When PYTHONPATH is set using an .env file, it will affect anything the extension does on your behalf and actions performed by the debugger, but it will not affect tools run in the terminal.

可以参考official docs.