我使用下面的设置

macOS v10.14 (Mojave) Python 3.7.1 Visual Studio Code 1.30 2.2.2 Pylint Django 2.1.4

我想使用linting使我在Visual Studio Code中的工作更容易一些。然而,对于每一个进口,我都有“未解决的进口”的状态。即使是默认的Django导入(即从Django .db导入模型)。

我认为这是因为它没有看到虚拟环境的Python文件。

一切都很好,但它开始变得烦人。

我选择的解释器都是Python的系统版本。它似乎根本看不到我的虚拟环境Python(它与我的工作空间不在同一个目录中,因此这部分是有意义的)。

如果我设置好python。设置中的PythonPath。Json文件,它只是忽略它,没有列出我的虚拟环境路径作为一个选项。我还尝试在我的全局Python设置中设置它,但它也没有显示。

有没有快速修复方法让它工作?


当前回答

这对我来说很管用:

打开命令面板(Ctrl + Shift + P)并选择“Python: Select Interpreter”。

这样做,你在Visual Studio Code中设置Python解释器。

其他回答

我正在使用以下设置:(在2021年4月)

Macos big sur vscode 水蟒3(环保版)

我在启动Django时遇到了这个错误。 因此,我执行这些步骤,这个错误就得到了解决。

步骤如下截图所示:

打开设置(工作区) 按照这张截图打开Python Path 现在,单击settings.json中的Edit 创建如下截图所示的路径/opt/anaconda3/bin/python

5. 现在,保存这个设置。json文件。 6. 重新启动vscode

此外,智能感知可能不会工作一段时间,保持等待一段时间,然后重新启动,然后vscode读取文件的新路径。

这个问题已经在GitHub上打开了:

Python无法解决导入问题#3840

MagnuesBrzenk和SpenHouet给出了两个非常有用的答案。

目前最好的解决方案是在项目根文件夹中创建一个.env文件。然后像这样添加一个PYTHONPATH:

PYTHONPATH=YOUR/MODULES/PATH

在你的设置中。json添加:

"python.envFile": ".env"

我有一个不同的解决方案:我的Visual Studio Code实例已经获取了存储在.venv中的virtualenv,但它使用了错误的Python二进制文件。它使用了.venv/bin/python3.7;使用蓝色状态栏中的切换器。

我把它改为使用.venv/bin/python,我所有的导入都正确解析了。

当我这样做的时候,我不知道Visual Studio Code在幕后做了什么,我也不明白为什么这导致了我的问题,但对我来说,这是一个比编辑我的工作空间设置更简单的解决方案。

我有一个库,在尝试使用Jedi语言服务时出错,没有它也能正常工作(即c#的那个)。

这个库是jsonslicer,它依赖于我安装在/usr/local/lib中的一个外部C库会不会跟这个有关?

我在Conda环境中安装了Jedi服务和库,并在Visual Studio中使用该环境。它在运行时和在我的终端上工作得很好,但在检查源文件中的问题时却不是这样,它显示为一个错误。

我曾以三种方式面对这个问题。虽然在这个问题的答案中,每个问题都有一个解决方案,但我只是想把它们放在一起。

First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment. This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here. The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that: { "python.pythonPath": "apis/bin/python" } This will basically tell Visual Studio Code to use the Python interpreter that is in your venv. The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app, from app.models import setup_db Verbally, import setup_db from models.py resides in the app folder.