Visual Studio Code (VSCode) 已成为 Python 开发的热门选择,其轻量级设计和强大的扩展性使其成为理想的 Python IDE。本指南将帮助你从零开始搭建一个高效的 Python 开发环境。
.exe
安装程序.dmg
安装程序.deb
、.rpm
或 Snap 包推荐安装 Python 3.8 以上版本:
Windows:
macOS:
brew install python
Linux (Ubuntu/Debian):
sudo apt update
sudo apt install python3 python3-pip python3-venv
打开终端或命令提示符,输入:
python --version # 或 python3 --version
pip --version # 或 pip3 --version
Ctrl+Shift+X
)Ctrl+Shift+P
(Windows/Linux)或 Cmd+Shift+P
(macOS)打开命令面板Python: Select Interpreter
虚拟环境可以为不同项目创建隔离的 Python 环境,避免依赖冲突。
打开 VSCode 的集成终端(Ctrl+
或 Terminal > New Terminal
)
导航到项目目录
创建虚拟环境:
Windows:
python -m venv .venv
macOS/Linux:
python3 -m venv .venv
激活虚拟环境:
Windows:
.\.venv\Scripts\activate
macOS/Linux:
source .venv/bin/activate
命令提示符或终端前应出现 (.venv)
如果你使用 Anaconda 或 Miniconda:
conda create -n myproject python=3.11
conda activate myproject
Python: Select Interpreter
)激活虚拟环境后,安装项目所需的包:
pip install package-name
对于多人协作项目,使用 requirements.txt 管理依赖:
创建 requirements.txt 文件:
numpy==1.24.3
pandas==2.0.2
matplotlib==3.7.1
安装依赖:
pip install -r requirements.txt
更新 requirements.txt:
pip freeze > requirements.txt
安装 linter:
pip install pylint
在 VSCode 中打开命令面板 (Ctrl+Shift+P
)
输入 Python: Select Linter
选择 pylint
安装 Black 或 autopep8:
pip install black
# 或
pip install autopep8
配置格式化器:
Python: Select Formatter
black
或 autopep8
启用保存时自动格式化(可选):
Ctrl+,
)editor.formatOnSave
VSCode 提供强大的 Python 调试功能:
创建 .vscode/launch.json
文件配置更复杂的调试场景:
Debug: Open launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
},
{
"name": "Python: Main File",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/main.py",
"console": "integratedTerminal",
"justMyCode": true
}
]
}
VSCode 提供了出色的 Jupyter Notebook 支持:
.ipynb
扩展名.ipynb
文件常用快捷键:
Shift+Enter
+Code
+Markdown
在 .vscode/settings.json
中配置 Python 路径和其他设置:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"--line-length", "88"
],
"editor.formatOnSave": true,
"python.analysis.typeCheckingMode": "basic",
"python.terminal.activateEnvironment": true
}
Preferences: Configure User Snippets
python.json
{
"Main function": {
"prefix": "main",
"body": [
"def main():",
" $0",
"",
"",
"if __name__ == \"__main__\":",
" main()"
],
"description": "Add main function"
},
"Print debug": {
"prefix": "pd",
"body": "print(f\"$1: {$1}\")",
"description": "Print debug"
}
}
VSCode 支持 Python 的多种测试框架:
安装测试框架:
pip install pytest
配置测试框架:
Python: Configure Tests
pytest
编写测试文件(如 test_module.py
):
def test_function():
assert 1 + 1 == 2
运行测试:
Python: Run All Tests
VSCode 内置了 Git 支持:
初始化 Git 仓库(如果尚未初始化):
git init
使用 VSCode 的源代码管理视图 (在左侧栏)
暂存、提交和推送更改
创建和切换分支
解决合并冲突
为 Python 项目创建 .gitignore
文件:
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Virtual environment
.venv/
venv/
ENV/
# Distribution / packaging
dist/
build/
*.egg-info/
# Jupyter Notebook
.ipynb_checkpoints
# VS Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# Environment variables
.env
pip install numpy pandas matplotlib seaborn scikit-learn jupyter
pip install flask django requests pytest-django
.env
文件管理环境变量pip install fastapi uvicorn pydantic requests
如果 VSCode 找不到 Python 解释器:
Ctrl+Shift+P
-> Python: Select Interpreter
)如果遇到 "module not found" 错误:
.vscode/settings.json
中配置 PYTHONPATH
: {
"terminal.integrated.env.windows": {
"PYTHONPATH": "${workspaceFolder}"
}
}
如果代码检查或格式化不工作:
创建 .vscode/tasks.json
来自动化常见任务:
{
"version": "2.0.0",
"tasks": [
{
"label": "Run Tests",
"type": "shell",
"command": "${command:python.interpreterPath}",
"args": ["-m", "pytest"],
"group": {
"kind": "test",
"isDefault": true
}
},
{
"label": "Lint Code",
"type": "shell",
"command": "${command:python.interpreterPath}",
"args": ["-m", "pylint", "src/"],
"problemMatcher": []
},
{
"label": "Generate Documentation",
"type": "shell",
"command": "${command:python.interpreterPath}",
"args": ["-m", "pdoc", "--html", "src", "-o", "docs/"],
"problemMatcher": []
}
]
}
提高效率的快捷键:
F5
:开始调试F9
:设置/取消断点Ctrl+Space
:触发自动完成Shift+Alt+F
:格式化文档Ctrl+Shift+P
:打开命令面板Ctrl+P
:快速打开文件Ctrl+
``:打开/关闭终端一个良好配置的 VS Code Python 环境可以显著提高开发效率。通过本指南,你已经学会了:
这个配置可以根据你的特定需求进一步定制,随着你的 Python 项目变得更加复杂,VSCode 的强大功能将帮助你保持高效和组织良好的开发环境。
除了核心的 Python 扩展外,以下扩展可以进一步提升开发体验:
Python Docstring Generator
"""
并按 Enter 即可IntelliCode
GitLens
Error Lens
REST Client
.http
文件发送请求,对 Flask/Django API 开发很有用### 测试 GET 请求
GET http://localhost:5000/api/users
### 测试 POST 请求
POST http://localhost:5000/api/users
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]"
}
Database Client
Docker
Remote Development
为大型项目建立合理的结构:
project_name/
├── .vscode/ # VSCode 配置
│ ├── launch.json
│ └── settings.json
├── src/ # 源代码
│ ├── __init__.py
│ ├── main.py # 应用入口
│ ├── module1/
│ │ ├── __init__.py
│ │ └── module1.py
│ └── module2/
│ ├── __init__.py
│ └── module2.py
├── tests/ # 测试文件
│ ├── __init__.py
│ ├── test_module1.py
│ └── test_module2.py
├── docs/ # 文档
│ └── index.md
├── scripts/ # 实用脚本
│ └── setup_db.py
├── data/ # 数据文件
│ ├── raw/
│ └── processed/
├── notebooks/ # Jupyter notebooks
│ └── exploration.ipynb
├── .gitignore
├── .env.example
├── pyproject.toml # 现代项目配置
├── README.md
└── requirements.txt # 或 requirements/
现代 Python 项目可以使用 pyproject.toml
替代传统的 setup.py
和 requirements.txt
:
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my_project"
version = "0.1.0"
description = "A sample Python project"
readme = "README.md"
requires-python = ">=3.8"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "[email protected]"},
]
dependencies = [
"numpy>=1.20.0",
"pandas>=1.3.0",
"matplotlib>=3.4.0",
]
[project.optional-dependencies]
dev = [
"pytest>=6.0",
"black>=21.5b2",
"pylint>=2.8.2",
]
[tool.pytest]
testpaths = ["tests"]
[tool.black]
line-length = 88
target-version = ["py38"]
[tool.pylint.messages_control]
disable = ["C0111", "C0103"]
安装依赖:
pip install -e ".[dev]"
调试部署在远程服务器上的应用:
在远程服务器上安装 debugpy
:
pip install debugpy
修改你的应用入口点:
import debugpy
debugpy.listen(("0.0.0.0", 5678))
print("Waiting for debugger attach...")
debugpy.wait_for_client()
在 VSCode 中配置 .vscode/launch.json
:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "your-server-ip",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/path/to/project/on/server"
}
]
}
]
}
提高调试效率:
条件断点:右键点击断点,选择 "Edit Breakpoint",添加表达式
i > 100
仅在变量 i
大于 100 时停止日志点:右键点击行号,选择 "Add Logpoint"
Value is {value}
在不停止程序的情况下记录信息表达式监视:在调试会话中添加表达式监视
安装性能分析工具:
pip install memory-profiler line-profiler
创建性能分析任务 .vscode/tasks.json
:
{
"version": "2.0.0",
"tasks": [
{
"label": "Profile Memory",
"type": "shell",
"command": "${command:python.interpreterPath}",
"args": ["-m", "memory_profiler", "${file}"],
"group": "test"
},
{
"label": "Profile Time",
"type": "shell",
"command": "kernprof",
"args": ["-l", "-v", "${file}"],
"group": "test"
}
]
}
在代码中添加装饰器:
# 内存分析
from memory_profiler import profile as memory_profile
@memory_profile
def memory_intensive_function():
# 代码...
# 时间分析
@profile # 不需要导入,kernprof会注入
def time_intensive_function():
# 代码...
使用命令面板运行任务:Tasks: Run Task
-> Profile Memory
或 Profile Time
.github/workflows/python-app.yml
文件:name: Python Application
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
pip install pytest pylint
- name: Lint with pylint
run: |
pylint $(find . -name "*.py" | grep -v "test_")
- name: Test with pytest
run: |
pytest
添加 .pre-commit-config.yaml
文件自动化代码质量检查:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies: [flake8-docstrings]
安装和启用:
pip install pre-commit
pre-commit install
实时协作编辑和调试:
使用 .vscode/settings.json
确保团队一致的编辑体验:
{
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--rcfile=.pylintrc"
],
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"--line-length", "88"
],
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"files.exclude": {
"**/__pycache__": true,
"**/.pytest_cache": true,
"**/*.pyc": true
},
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestArgs": [
"tests"
]
}
使用 Pull Request 模板 (.github/pull_request_template.md
):
## 描述
请描述此 PR 中的更改及其目的。
## 相关问题
修复 #(问题号)
## 更改类型
- [ ] 错误修复(非破坏性更改,修复问题)
- [ ] 新功能(非破坏性更改,添加功能)
- [ ] 破坏性更改(会导致现有功能无法如预期工作的更改)
## 清单
- [ ] 我的代码遵循项目的代码风格
- [ ] 我已经添加了注释,特别是在难以理解的地方
- [ ] 我已经对变更进行了相应的文档更新
- [ ] 我添加了测试,证明我的修复有效或新功能如预期工作
- [ ] 新的和现有的单元测试在进行更改时通过
管理不同环境的配置:
安装 python-dotenv:
pip install python-dotenv
创建环境配置文件:
.env.development
.env.test
.env.production
在应用中加载配置:
import os
from dotenv import load_dotenv
# 根据环境选择正确的.env文件
env = os.getenv("ENVIRONMENT", "development")
load_dotenv(f".env.{env}")
# 使用环境变量
database_url = os.getenv("DATABASE_URL")
debug_mode = os.getenv("DEBUG", "False") == "True"
在 VSCode 中设置环境:
// launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Development",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/main.py",
"env": {
"ENVIRONMENT": "development"
}
},
{
"name": "Python: Production",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/main.py",
"env": {
"ENVIRONMENT": "production"
}
}
]
}
安装 Django 扩展:
特定配置 .vscode/settings.json
:
{
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
"--django-settings-module=myproject.settings"
],
"files.associations": {
"**/*.html": "html",
"**/templates/**/*.html": "django-html",
"**/templates/**/*": "django-txt"
},
"emmet.includeLanguages": {
"django-html": "html"
}
}
Django 专用调试配置:
{
"version": "0.2.0",
"configurations": [
{
"name": "Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"runserver"
],
"django": true,
"justMyCode": true
},
{
"name": "Django Shell",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"shell"
],
"django": true,
"justMyCode": true
}
]
}
{
"version": "0.2.0",
"configurations": [
{
"name": "Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "app.py",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
],
"jinja": true
}
]
}
安装 Plot Viewer 扩展
添加数据科学依赖:
pip install matplotlib seaborn plotly pandas numpy scikit-learn
Jupyter 用户界面优化:
{
"notebook.cellToolbarLocation": {
"default": "right",
"jupyter-notebook": "left"
},
"notebook.lineNumbers": "on",
"notebook.outlineButtonEnabled": true,
"notebook.consolidatedRunButton": true,
"notebook.showFoldingControls": "always"
}
数据探索专用启动配置:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (with args)",
"type": "python",
"request": "launch",
"program": "${file}",
"args": ["--data", "${workspaceFolder}/data/dataset.csv"],
"console": "integratedTerminal"
}
]
}
自定义快捷键:打开键盘快捷方式 (Ctrl+K Ctrl+S
),添加常用操作的快捷键
使用代码折叠:通过添加特殊注释组织代码区域
# region 数据预处理
def preprocess_data():
# 代码...
# endregion
工作区管理:使用多个工作区文件 (.code-workspace
) 管理不同项目
使用工作区范围内的搜索:通过 Ctrl+Shift+F
进行全项目搜索
通过本指南中介绍的进阶技术和最佳实践,你可以将 VSCode 打造成一个功能完备、高效的 Python 开发环境。无论是单个开发者还是团队协作,无论是 Web 开发还是数据科学,VSCode 都能提供强大的支持。
随着项目的发展,定期审视和更新开发环境配置,不断尝试新工具和技术,将帮助你保持高效的开发节奏和代码质量。记住,最好的开发环境是能够适应你的工作流程并随着项目需求而不断发展的环境。