如何在 Visual Studio Code 中为 Python 设置虚拟环境?

如何在 Visual Studio Code 中为 Python 设置虚拟环境?

问题描述:

在我的项目文件夹中,我创建了一个 venv 文件夹:

In my project folder I created a venv folder:

python -m venv venv

当我在 Visual Studio Code 中运行命令 select python interpreter 时,我的 venv 文件夹没有显示.我像建议的此处那样上一级,但Visual Studio Code没有看到我的虚拟翻译.

When I run command select python interpreter in Visual Studio Code, my venv folder is not shown. I went one level up like suggested here, but Visual Studio Code doesn't see my virtual interpreter.

我错过了什么?

P.S.:

  • 我已经使用 Visual Studio Code 一段时间了,并找到了另一种在 Visual Studio Code 中显示虚拟环境的方法.

  • I have been using Visual Studio Code for a while now and found an another way to show virtual environments in Visual Studio Code.

通过命令提示符转到 venv 所在的父文件夹.

Go to the parent folder in which venv is there through a command prompt.

输入 code .回车.[它适用于我的 Windows 和 Linux.]

Type code . and Enter. [It is working on both Windows and Linux for me.]

这也应该显示该文件夹中存在的虚拟环境.

That should also show the virtual environments present in that folder.

原答案

每次使用 venv 处理 Visual Studio Code 时,我几乎都会遇到同样的问题.我按照以下步骤操作:

I almost run into same problem every time I am working on Visual Studio Code using venv. I follow the below steps:

  1. 转到菜单文件首选项设置.

点击工作区设置.

Files:Association 下的 JSON: Schemas 部分,您将找到 Edit in settings.json.点击那个.

Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json. Click on that.

在工作区设置下更新"python.pythonPath":"Your_venv_path/bin/python".(对于 Windows):在工作区设置下更新 "python.pythonPath":"Your_venv_path/Scripts/python.exe".

Update "python.pythonPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.pythonPath": "Your_venv_path/Scripts/python.exe" under workspace settings.

重新启动 Visual Studio Code,以防它仍然没有显示您的 venv.

Restart Visual Studio Code in case if it still doesn't show your venv.