完整教程:Python 编辑器:Visual Studio Code(进阶篇)

对于进阶开发者,尤其是在团队协作环境中,除了 VS Code 的基本运行,还需要关注环境隔离、依赖管理、调试技巧、代码规范、版本控制与远程开发等方面。

一、虚拟环境与依赖管理

1、创建虚拟环境

在 Python 项目中,每个项目应使用独立的虚拟环境来管理依赖,避免不同项目之间的库冲突。

Windows(CMD):

python -m venv .venv.\.venv\Scripts\activate.bat

Windows(PowerShell):

python -m venv .venv.\.venv\Scripts\Activate.ps1

如首次执行报错,可运行:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

macOS/Linux:

python3 -m venv .venvsource .venv/bin/activate

激活后,终端前缀会显示 (.venv)。

提示:

虚拟环境目录常见写法有 .venv/ 或 venv/,本文示例统一使用 .venv/,需与 VS Code 配置保持一致。

2、在 VS Code 中选择或切换虚拟环境

打开命令面板(Ctrl + Shift + P)→ 输入 Python: Select Interpreter → 选择 ./.venv 对应的解释器。

VS Code 会自动在 .vscode/settings.json 中记录该解释器路径。

3、安装依赖

方法一:在 VS Code 终端中安装

推荐使用解释器绑定的 pip 安装:

python -m pip install requests matplotlib pandas black

方式 2:使用 requirements.txt

在项目根目录中创建 requirements.txt。

内容示例:

requests==2.31.0pandas==1.5.3

安装(推荐同样使用解释器绑定的 pip):

python -m pip install -r requirements.txt

提示:

团队协作时尽量固定依赖版本,避免环境差异。

4、推荐的目录结构

my_project/│├── .git/              ← Git 版本控制├── .vscode/           ← VS Code 项目配置│   └── settings.json├── .venv/             ← 虚拟环境├── requirements.txt   ← 依赖清单├── src/               ← 源代码│   └── my_package/│       ├── __init__.py│       ├── module_a.py│       └── module_b.py└── tests/             ← 测试代码

 .gitignore 示例:

# venv.venv/venv/
# Python__pycache__/*.py[cod]*.pyo
# tooling / testing.pytest_cache/.mypy_cache/.coveragehtmlcov/
# VS Code.vscode/*!.vscode/settings.json!.vscode/launch.json!.vscode/extensions.json
# env files.env

5、进阶工具

(1)Poetry

更现代的依赖管理工具(基于 pyproject.toml)。

poetry add requests

(2)Conda

适合数据科学项目,便于管理科学计算库。

二、调试配置

VS Code 使用 .vscode/launch.json 来管理调试配置。

示例:

{  "version": "0.2.0",  "configurations": [    {      "name": "Python: main.py",      "type": "python",      "request": "launch",      "program": "${workspaceFolder}/src/main.py",      "console": "integratedTerminal",      "cwd": "${workspaceFolder}",      "args": ["--mode", "test", "--verbose"],      "envFile": "${workspaceFolder}/.env",      "justMyCode": true,      "subProcess": true    }  ]}

功能说明:

1、定义程序入口点、运行参数和调试方式。

2、可共享给团队,保证调试流程一致。

3、支持命令行参数、加载 .env 环境变量。

4、支持条件断点,仅在满足条件时中断。

三、项目设置

项目设置保存在 .vscode/settings.json 中,用于统一团队的开发体验。

示例:使用 Black 自动格式化代码。

1、安装 Black 库及插件

(1)在项目虚拟环境安装 black 库:

python -m pip install black

(2)在VS Code 的“扩展”面板中找到并安装“Black Formatter”插件。

说明:

只装 Black Formatter 插件,没有 Black 库 → 无法运行。

只装 Black 库,不装 Black Formatter 插件 → 可以用命令行格式化,但 VS Code 里没法一键调用。

2、设置保存文件时自动触发格式化

在项目下编辑 .vscode/settings.json 文件。

Windows:

{  "python.defaultInterpreterPath": "${workspaceFolder}\\.venv\\Scripts\\python.exe",  "editor.formatOnSave": true,  "[python]": {    "editor.defaultFormatter": "ms-python.black-formatter",    "editor.formatOnSave": true  },  "editor.codeActionsOnSave": { "source.organizeImports": true },  "python.testing.pytestEnabled": true,  "python.testing.pytestArgs": ["-q", "tests"]}

macOS / Linux:

{  "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",  "editor.formatOnSave": true,  "[python]": {    "editor.defaultFormatter": "ms-python.black-formatter",    "editor.formatOnSave": true  },  "editor.codeActionsOnSave": { "source.organizeImports": true },  "python.testing.pytestEnabled": true,  "python.testing.pytestArgs": ["-q", "tests"]}

3、补充工具

isort:自动整理 import 顺序。

flake8 / pylint:代码规范检查。

pytest:测试发现与运行。

统一风格配置(pyproject.toml):

[tool.black]line-length = 100target-version = ["py311"]
[tool.isort]profile = "black"

四、Git 版本控制集成

VS Code 内置 Git 支持,可直接完成初始化、提交、分支、同步等操作。

1、初始化 Git 仓库

在 VS Code 左侧点击“源代码管理”图标 → 点击“初始化仓库”按钮。

或命令行执行:

git init

2、提交更改

在“源代码管理”面板中,勾选修改文件 → 输入提交信息 → 点击 ✓ 提交。

命令行:

git add .git commit -m "初始化项目"

3、分支管理

左下角分支图标可切换/新建分支。

命令行:

git switch -c feature-x

4、远程仓库同步

添加远程地址:

git remote add origin https://github.com/username/repo.git

推送:

git push -u origin main

拉取:

git pull origin main

5、推荐插件

GitLens:查看提交历史、作者信息。

Git Graph:可视化分支结构。

如果出现“Author identity unknown”,可设置全局身份:

git config --global user.name "Your Name"git config --global user.email "you@example.com"

6、禁用 Git 集成

如果完全不需要 Git,可以在设置中加入:

"git.enabled": false

五、远程开发与容器支持

对于团队协作或需要统一环境的场景,推荐使用 Remote Development 插件:

Remote-SSH:在远程服务器上开发。

Dev Containers:通过 .devcontainer/devcontainer.json 定义开发容器,实现“一键构建统一环境”。

示例:

{  "name": "Python Dev",  "image": "python:3.11",  "settings": {    "python.defaultInterpreterPath": "/usr/local/bin/python"  },  "postCreateCommand": "python -m pip install --upgrade pip && python -m pip install -r requirements.txt",  "customizations": {    "vscode": {      "extensions": [        "ms-python.python",        "ms-python.black-formatter",        "ms-python.isort",        "ms-python.vscode-pylance",        "ms-azuretools.vscode-docker"      ]    }  }}

六、常见问题与解决方案

1、虚拟环境未被识别

Ctrl + Shift + P → Python: Select Interpreter → 选择 .venv。

2、pip 安装太慢

临时:

pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

全局配置:

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

小结

在 VS Code 中进行 Python 进阶开发,需要关注虚拟环境隔离与依赖管理,使用 launch.json 配置统一调试流程,通过 Black、isort、flake8 等工具保持一致的代码规范,并结合 Git 与远程开发容器实现团队协作与环境一致性。通过这些实践,既能避免依赖冲突,又能提升协作效率和项目质量。

图片

“点赞有美意,赞赏是鼓励”

posted @ 2025-09-29 16:40  yxysuanfa  阅读(13)  评论(0)    收藏  举报