🐍 第01课:环境搭建

—— 工欲善其事,必先利其器

🏆 Python3.12+venv+pip配置完成
✅ Python验证通过

📌 本课目标

1️⃣ 为什么需要虚拟环境?

想象一下:项目A需要 requests 2.28,项目B需要 requests 2.31。如果都装在全局环境,版本冲突不可避免。虚拟环境就是每个项目的"独立房间",互不干扰。

💡 核心概念:虚拟环境 ≠ 复制 Python 解释器。venv 使用符号链接引用原始 Python,只隔离第三方包,非常轻量。

2️⃣ 安装 Python 3.12

Ubuntu/Debian

# 添加 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

macOS

# 使用 Homebrew
brew install python@3.12
python3.12 --version

Windows

# 从 python.org 下载安装包
# 安装时勾选 "Add Python to PATH"
python --version

3️⃣ 创建与激活虚拟环境

# 创建项目目录
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/

4️⃣ pip 包管理器

# 查看已安装的包
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

5️⃣ 配置国内镜像源

默认的 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

6️⃣ 验证环境完整性

运行以下 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()
================================================== 🐍 Python 环境验证报告 ================================================== ✅ Python 版本: 3.12.3 📦 标准库模块检查: ✅ json ✅ csv ✅ pathlib ✅ datetime ✅ logging ✅ argparse ✅ subprocess ✅ re ✅ collections ✅ itertools ✅ pip 版本: 24.0 ✅ 默认编码: utf-8 ✅ 文件系统编码: utf-8 🖥️ 平台: Linux 6.8.0-101-generic 🏗️ 架构: x86_64 ================================================== 🎉 环境验证完成! ==================================================

7️⃣ 推荐开发工具

工具类型特点
VS Code编辑器轻量、插件丰富、Python 扩展强大
PyCharm CommunityIDE专业 Python IDE、智能补全
vim/nvim编辑器终端开发、LSP 支持
Jupyter Notebook交互环境数据探索、可视化首选

8️⃣ VS Code 推荐扩展

# 在 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

9️⃣ 项目的标准结构

my_project/
├── .venv/              # 虚拟环境(不提交 Git)
├── .gitignore          # 忽略规则
├── requirements.txt    # 依赖清单
├── README.md           # 项目说明
├── src/                # 源代码
│   ├── __init__.py
│   └── main.py
├── tests/              # 测试代码
│   └── test_main.py
└── data/               # 数据文件

🔑 本课要点

  1. 始终使用虚拟环境——避免版本冲突和环境污染
  2. pip freeze > requirements.txt——锁定依赖版本
  3. 配置国内镜像——pip 安装速度提升 10x+
  4. Python 3.12+——享受最新特性和性能提升
  5. UTF-8 为默认编码——告别编码地狱