VSCode 终端配置与 Python 虚拟环境使用指南

VSCode 终端配置与 Python 虚拟环境使用指南

一、设置 VSCode 在项目中默认使用的终端

方法:

  1. 打开 VSCode
  2. 打开命令面板(Ctrl+Shift+P),输入"Preferences: Open Settings (JSON)"并选择,打开 settings.json 文件
  3. 在 settings.json 中,添加或修改以下设置:
json 复制代码
{
  "terminal.integrated.defaultProfile.windows": "Git Bash", // 对于 Windows,可选值有 "Command Prompt", "PowerShell", "Git Bash" 等
  "terminal.integrated.profiles.windows": {
    "PowerShell": {
      "source": "PowerShell",
      "args": []
    },
    "Command Prompt": {
      "path": [
        "${env:windir}\\Sysnative\\cmd.exe",
        "${env:windir}\\System32\\cmd.exe"
      ],
      "args": []
    },
    "Git Bash": {
      "source": "Git Bash"
    }
  },
  // 可选:自动激活虚拟环境
  "python.terminal.activateEnvironment": true
}

二、激活 Python 虚拟环境

在不同终端中激活虚拟环境的方法:

1. 在 Command Prompt (CMD) 中激活:
cmd 复制代码
cd g:\code
.\.venv\Scripts\activate
2. 在 PowerShell 中激活:
powershell 复制代码
cd g:\code
.\.venv\Scripts\Activate.ps1

注意:如果遇到执行策略问题,可以先运行 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process 临时允许脚本执行

3. 在 Git Bash 中激活:
bash 复制代码
cd /g/code
source .venv/Scripts/activate

验证虚拟环境是否成功激活:

  • 命令提示符前会显示 (.venv) 标识
  • 运行 python -c "import sys; print(sys.executable)" 应显示虚拟环境中的 Python 路径

三、直接使用虚拟环境中的 Python 解释器

无需激活环境,直接使用完整路径调用虚拟环境的 Python 解释器:

在 CMD 或 PowerShell 中:

复制代码
g:\code\.venv\Scripts\python.exe your_script.py

在 Git Bash 中:

bash 复制代码
/g/code/.venv/Scripts/python.exe your_script.py

四、使用虚拟环境中的 pip 安装包

方法 1:先激活环境再安装

cmd 复制代码
cd g:\code
.\.venv\Scripts\activate
pip install package_name

方法 2:直接使用虚拟环境的 pip

cmd 复制代码
g:\code\.venv\Scripts\pip.exe install package_name

五、常见问题解决

  1. PowerShell 执行脚本被禁止

    • 运行 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
  2. Git Bash 中路径错误

    • 使用 /g/ 而不是 g:\ 格式的路径
  3. 虚拟环境激活后不生效

    • 检查 Python 解释器路径是否正确
    • 确认虚拟环境已正确创建
相关推荐
共享家95271 天前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Hgfdsaqwr1 天前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
一晌小贪欢1 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模1 天前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
Halo_tjn1 天前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr1 天前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448911 天前
export_onnx.py_0130
pytorch·python·深度学习
s1hiyu1 天前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_763472461 天前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
无垠的广袤1 天前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:缺陷检测
linux·人工智能·python·opencv·开发板