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 解释器路径是否正确
    • 确认虚拟环境已正确创建
相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero072 天前
Jev 与 Laya
python·语言模型