—— 工欲善其事,必先利其器
想象一下:项目A需要 requests 2.28,项目B需要 requests 2.31。如果都装在全局环境,版本冲突不可避免。虚拟环境就是每个项目的"独立房间",互不干扰。
# 添加 deadsnakes PPA(官方源可能没有最新版)
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.12 python3.12-venv python3.12-dev
# 验证安装
python3.12 --version
# Python 3.12.3
# 使用 Homebrew
brew install python@3.12
python3.12 --version
# 从 python.org 下载安装包
# 安装时勾选 "Add Python to PATH"
python --version
# 创建项目目录
mkdir my_project && cd my_project
# 创建虚拟环境(推荐命名 .venv)
python3.12 -m venv .venv
# 激活虚拟环境
# Linux/macOS:
source .venv/bin/activate
# Windows:
# .venv\Scripts\activate
# 激活后终端会显示 (.venv) 前缀
(.venv) $ which python
# /home/user/my_project/.venv/bin/python
deactivate 命令。永远不要把 .venv/ 目录提交到 Git!在 .gitignore 中添加 .venv/。
# 查看已安装的包
pip list
# 安装包
pip install requests
# 安装指定版本
pip install requests==2.31.0
# 升级包
pip install --upgrade requests
# 卸载包
pip uninstall requests
# 导出依赖
pip freeze > requirements.txt
# 从依赖文件安装
pip install -r requirements.txt
默认的 PyPI 服务器在国外,下载速度可能很慢。配置国内镜像可以大幅提速。
# 临时使用镜像
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
# 永久配置(推荐)
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn
# 常用镜像源
# 清华: https://pypi.tuna.tsinghua.edu.cn/simple
# 阿里: https://mirrors.aliyun.com/pypi/simple
# 豆瓣: https://pypi.doubanio.com/simple
运行以下 Python 脚本,确认所有组件正常工作:
#!/usr/bin/env python3
"""环境搭建验证脚本"""
import sys
import platform
import importlib
from pathlib import Path
def check_python_version():
"""检查 Python 版本"""
version = sys.version_info
assert version.major == 3 and version.minor >= 12, \
f"需要 Python 3.12+,当前 {version.major}.{version.minor}"
print(f"✅ Python 版本: {version.major}.{version.minor}.{version.micro}")
def check_venv():
"""检查是否在虚拟环境中"""
in_venv = hasattr(sys, 'real_prefix') or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
if in_venv:
print(f"✅ 虚拟环境已激活: {sys.prefix}")
else:
print("⚠️ 未在虚拟环境中运行(建议使用 venv)")
def check_stdlib_modules():
"""检查标准库模块可用性"""
modules = ['json', 'csv', 'pathlib', 'datetime', 'logging',
'argparse', 'subprocess', 're', 'collections', 'itertools']
for mod in modules:
try:
importlib.import_module(mod)
print(f" ✅ {mod}")
except ImportError:
print(f" ❌ {mod} 不可用")
def check_pip():
"""检查 pip 可用性"""
try:
import pip
print(f"✅ pip 版本: {pip.__version__}")
except ImportError:
print("❌ pip 不可用")
def check_encoding():
"""检查默认编码"""
encoding = sys.getdefaultencoding()
print(f"✅ 默认编码: {encoding}")
fs_encoding = sys.getfilesystemencoding()
print(f"✅ 文件系统编码: {fs_encoding}")
def main():
print("=" * 50)
print("🐍 Python 环境验证报告")
print("=" * 50)
print()
check_python_version()
print()
check_venv()
print()
print("📦 标准库模块检查:")
check_stdlib_modules()
print()
check_pip()
print()
check_encoding()
print()
print(f"🖥️ 平台: {platform.system()} {platform.release()}")
print(f"🏗️ 架构: {platform.machine()}")
print()
print("=" * 50)
print("🎉 环境验证完成!")
print("=" * 50)
if __name__ == "__main__":
main()
| 工具 | 类型 | 特点 |
|---|---|---|
| VS Code | 编辑器 | 轻量、插件丰富、Python 扩展强大 |
| PyCharm Community | IDE | 专业 Python IDE、智能补全 |
| vim/nvim | 编辑器 | 终端开发、LSP 支持 |
| Jupyter Notebook | 交互环境 | 数据探索、可视化首选 |
# 在 VS Code 中安装以下扩展
code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension ms-python.debugpy
code --install-extension charliermarsh.ruff
code --install-extension mtxr.sqltools
my_project/
├── .venv/ # 虚拟环境(不提交 Git)
├── .gitignore # 忽略规则
├── requirements.txt # 依赖清单
├── README.md # 项目说明
├── src/ # 源代码
│ ├── __init__.py
│ └── main.py
├── tests/ # 测试代码
│ └── test_main.py
└── data/ # 数据文件