我使用下面的设置

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解释器。

其他回答

对我来说,如果我将python、pylint和autopep8的路径设置为本地环境路径,它就可以工作。

在你的工作区中添加/修改如下内容:

"python.pythonPath": "...\\your_path\\.venv\\Scripts\\python.exe",
"python.linting.pylintPath": "...\\your_path\\.venv\\Scripts\\pylint.exe",
"python.formatting.autopep8Path": "...\\your_path\\.venv\\Scripts\\autopep8.exe",

保存并使用工作区重新启动VS Code。 完成了!

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

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

给出以下示例项目结构:

workspaceRootFolder .vscode …其他文件夹 codeFolder

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

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

我似乎有这个问题,因为django安装在我的基本虚拟环境,而不是我实际使用的项目。这基本上导致它工作,但显示错误,不能正确自动完成。

要解决我简单

打开Anaconda Navigator 单击左侧菜单中的环境 选择项目使用的虚拟环境 在虚拟环境中,点击绿色三角形(一旦加载)并选择“打开终端” 运行'pip install django'

完成后,你可以回到VS Code,切换python环境到base,然后回到VS Code左下角你想要的环境。

错误应该消失,自动补全应该工作。

我已经通过Ctrl + Shift + P解决了导入错误。 输入“首选项设置”,并选择选项首选项打开设置(JSON)

并添加一行“python”。pythonPath环境”:“/ usr / bin /”

因此JSON内容应该是这样的:

{
    "python.pythonPath": "/usr/bin/"
}

如果存在其他配置行,则保留它们。 这将导入使用PIP自动完成安装的所有模块。

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

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.