我使用下面的设置

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设置中设置它,但它也没有显示。

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


当前回答

之前的答案对我都没用。将下面两行添加到我的设置中。Json文件,然而。

"python.analysis.disabled": [
    "unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]

第一行实际上只是隐藏了检测错误。当然这不是一个永久的解决方案,但可以让屏幕变得整洁。

这个答案给了我第二行:VS Code PyLint错误E0602(未定义的变量)与ProtoBuf编译的Python结构

也许比我更懂Python的人能再解释一下。

其他回答

对我来说,这个问题与我正在做的项目有关。我花了一段时间才弄明白,所以我希望这能帮到你:

原文件夹结构:

    root/
    __init__.py  # Empty

        folder/
            __init__.py # Empty

            sub_folder_b/
                my_code.py
            sub_folder_c/
                another_code.py

在another_code.py:

from folder.sub_folder_b import my_code.py

这并没有触发Visual Studio Code中的智能感知,但它确实执行得很好。

另一方面,在导入路径上添加“root”,确实使智能感知工作,但在执行时引发ModuleNotFoundError:

from root.folder.sub_folder_b import my_code.py

解决方案是删除“folder”目录中的_init_.py文件,只留下位于/root目录下的_init_.py文件。

这是因为Visual Studio Code将当前文件夹视为主文件夹,而不是实际的主文件夹。

快速修复的方法是提供主文件夹的解释器路径。

按Command + Shift + P(或按Ctrl + Shift + P在大多数其他系统)。

Python解释器类型

从可用选项中选择安装Python的路径。

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

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.

两年之后,我遇到了这个烦人的问题。我所能看到的是一些非常复杂的变通办法。这里有一些简单的步骤,对于那些稍后可能遇到这种情况的人来说:

在VS Code的底部,你可以看到列出的Python版本,只需点击那里 将出现“选择解释器窗口” 点击第一个选项“选择解释器路径”,并导航到包含虚拟环境的文件夹路径

这就是你所需要做的,避免在VS Code中篡改这些设置,如果不小心处理,可能会变得非常复杂。

我能够通过在.vscode\settings.json中启用jedi来解决这个问题

"python.jediEnabled": true

参考来自https://github.com/Microsoft/vscode-python/issues/3840#issuecomment-456017675