我使用下面的设置

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

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


当前回答

我有一个问题,我创建的模块的导入没有找到。我觉得我尝试了许多方法来确保python解释器的选择是正确的,但没有用。通过编辑设置,我找到了一个适合我的答案。Python>检测>Pylint参数并添加init-hook…

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

此解决方案在PyLint“无法导入”错误中找到-如何设置PYTHONPATH?。我没有创建和编辑pylintrc,而是使用VS Code GUI添加了上面的内容。

其他回答

如果你的设置中有这个代码。Json文件,删除它:

{
    "python.jediEnabled": false
}

除了这个,其他的解决方案都不奏效。替换设置中的“Pylance”或“Microsoft”。Json解决了我的问题。

"python.languageServer": "Jedi"

我的解决方案

此解决方案仅适用于当前项目。

In the project root, create folder .vscode Then create the file .vscode/settings.json In the file setting.json, add the line (this is for Python 3) { "python.pythonPath": "/usr/local/bin/python3", } This is the example for Python 2 { "python.pythonPath": "/usr/local/bin/python", } If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location. This example works for dockerized Python - Django.

Shinebayar G的解决方案是可行的,但另一个解决方案更优雅一些:

从Python复制未解决的导入问题#3840:

给出以下示例项目结构:

workspaceRootFolder .vscode …其他文件夹 codeFolder

我解决这个问题的方法是:

进入工作区文件夹(这里是workspaceRootFolder)并创建一个.env文件 在这个空的.env文件中,添加一行PYTHONPATH=codeFolder(将codeFolder替换为文件夹名称) 添加“python。envFile”:“$ {workspaceFolder} /。到settings.json中 重新启动Visual Studio代码

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

原文件夹结构:

    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文件。