跳转到内容

Python 学习概要

语言特性

Python 是一种解释型、强类型、动态类型的高级编程语言,以简洁优雅的语法和丰富的生态著称。

核心特点

特点说明
简洁易读强制缩进、语法简洁,接近自然语言
动态类型变量无需声明类型,运行时自动推断
多范式支持面向对象、函数式、过程式编程
丰富生态PyPI 上有数十万个第三方包
跨平台支持 Windows、Linux、macOS

学习路径

基础阶段

  1. 语法基础

    • 变量与数据类型(int, float, str, bool)
    • 流程控制(if/elif/else, for, while)
    • 函数定义与调用
    • 模块与包管理
  2. 数据结构

    • 列表(list):有序可变序列
    • 元组(tuple):有序不可变序列
    • 字典(dict):键值对映射
    • 集合(set):无序不重复集合
  3. 面向对象

    • 类与实例
    • 继承与多态
    • 魔术方法(__init__, __str__, __repr__ 等)
    • 数据类(dataclass)

进阶阶段

  1. 高级特性

    • 列表推导式 / 字典推导式 / 生成器表达式
    • 迭代器与生成器(yield)
    • 装饰器(decorator)
    • 上下文管理器(with 语句)
    • 类型注解(Type Hints)
  2. 异步编程

    • asyncio 事件循环
    • async/await 语法
    • 异步 I/O 操作
    • aiohttp / httpx 异步 HTTP 客户端
  3. 并发编程

    • threading 多线程
    • multiprocessing 多进程
    • concurrent.futures 线程池/进程池
    • GIL(全局解释器锁)的理解与应对

应用阶段

  1. Web 开发

    • FastAPI:现代高性能 Web 框架
    • Django:全功能 Web 框架
    • Flask:轻量级 Web 框架
  2. 数据处理

    • pandas:数据分析与处理
    • NumPy:数值计算
    • Matplotlib / Plotly:数据可视化
  3. DevOps & 自动化

    • subprocess:系统命令调用
    • paramiko / Fabric:SSH 自动化
    • kubernetes-client:K8s 集群操作
  4. AI / ML

    • scikit-learn:机器学习
    • PyTorch / TensorFlow:深度学习
    • LangChain:LLM 应用开发

包管理工具

pip

Python 标准包管理器:

bash
# 安装包
pip install package_name

# 安装指定版本
pip install package_name==1.0.0

# 导出依赖
pip freeze > requirements.txt

# 从文件安装依赖
pip install -r requirements.txt

uv

高性能 Python 包管理器(Rust 实现):

bash
# 初始化项目
uv init my-project

# 添加依赖
uv add requests

# 运行脚本
uv run python main.py

详见 uv 包管理器

虚拟环境

bash
# venv(标准库)
python -m venv .venv
source .venv/bin/activate  # Linux/macOS
.venv\Scripts\activate     # Windows

# uv(推荐)
uv venv
source .venv/bin/activate

如何发现和选择 Python 包

写 Python 最常见的问题就是:"我想做 X,该用哪个包?"

按场景找包

你想做什么搜索关键词推荐包
发 HTTP 请求python http requesthttpx, requests
操作 K8spython kuberneteskubernetes
操作数据库python mysql / postgresqlsqlalchemy, psycopg
写命令行工具python cliclick, typer
解析 YAML/JSONpython yamlpyyaml (标准库 json 够用)
读写 Excelpython excelopenpyxl
SSH 远程执行python sshparamiko, fabric
定时任务python cron / scheduleschedule, apscheduler
调用 LLMpython openai / anthropicopenai, anthropic, litellm

找包的渠道

  1. PyPI 搜索(最直接)

    • 访问 pypi.org,搜索关键词
    • 看下载量、最后更新时间、支持的 Python 版本
  2. GitHub 搜索

    • python + 你的需求,按 star 排序
    • 看 Issues 活跃度和最近 commit 时间
  3. 问 AI(最快)

    • 直接问:"Python 操作 Kubernetes 用什么包?"
    • AI 会给你推荐,但要注意它可能推荐过时的包,去 PyPI 验证一下
  4. 标准库优先

    • Python 标准库已经覆盖了很多场景,不需要装第三方包,详见下方 常用标准库速查

判断一个包值不值得用

装包之前看这几点:

指标好的信号危险信号
下载量月下载量几十万+月下载量几百
最近更新最近 6 个月内有 release超过 2 年没更新
Python 支持支持 3.10+只支持 3.6/3.7
文档有完整文档和示例只有 README 一句话
依赖依赖少(0-3 个)依赖链很长(几十个)
维护者有组织或活跃社区维护个人项目,长期不回复 Issue

快速验证命令

bash
# 查看包的信息
pip show kubernetes

# 查看包的依赖(依赖越少越好)
pipdeptree -p kubernetes

# 在 PyPI 上查看下载量
# https://pypi.org/project/kubernetes/

安装前先看看包里有什么

bash
# 不安装,只下载看看
pip download kubernetes --no-deps

# 或者直接在 PyPI 页面看源码和文档

常用标准库速查

Python 自带的标准库不需要 pip installimport 就能用。以下是日常开发中最常用的:

json — JSON 读写

python
import json

# Python 对象 → JSON 字符串
data = {"name": "nginx", "replicas": 3}
json_str = json.dumps(data, ensure_ascii=False, indent=2)

# JSON 字符串 → Python 对象
parsed = json.loads(json_str)

# 直接读写文件
with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

pathlib — 文件路径操作

python
from pathlib import Path

# 创建路径对象(比 os.path 更直观)
p = Path("/tmp/deploy") / "nginx.yaml"  # /tmp/deploy/nginx.yaml

# 常用属性
p.name       # "nginx.yaml"
p.stem       # "nginx"
p.suffix     # ".yaml"
p.parent     # Path("/tmp/deploy")

# 判断
p.exists()   # 是否存在
p.is_file()  # 是否是文件
p.is_dir()   # 是否是目录

# 操作
p.mkdir(parents=True, exist_ok=True)  # 递归创建目录
p.read_text(encoding="utf-8")         # 读文件内容
p.write_text("hello", encoding="utf-8")  # 写文件

# 遍历
for f in Path(".").glob("*.py"):
    print(f)

subprocess — 调用系统命令

python
import subprocess

# 执行命令并获取输出
result = subprocess.run(
    ["kubectl", "get", "pods", "-n", "default"],
    capture_output=True,       # 捕获 stdout 和 stderr
    text=True,                 # 输出为字符串而非字节
    check=True                 # 命令失败时抛异常
)
print(result.stdout)

# 执行命令但不关心输出
subprocess.run(["systemctl", "restart", "nginx"], check=True)

# 执行 Shell 命令(谨慎使用,注意注入风险)
result = subprocess.run(
    "kubectl get pods | grep Running",
    shell=True, capture_output=True, text=True
)

os — 系统环境与文件操作

python
import os

# 环境变量
db_host = os.getenv("DB_HOST", "localhost")  # 带默认值
os.environ["MY_VAR"] = "hello"               # 设置环境变量

# 路径操作(简单场景用 os,复杂场景用 pathlib)
os.listdir("/tmp")          # 列出目录内容
os.remove("/tmp/test.txt")  # 删除文件
os.rename("old.txt", "new.txt")  # 重命名

# 系统信息
os.name       # "nt"(Windows) 或 "posix"(Linux/macOS)
os.getcwd()   # 当前工作目录

argparse — 命令行参数解析

python
import argparse

parser = argparse.ArgumentParser(description="K8s Pod 清理工具")
parser.add_argument("-n", "--namespace", default="default", help="命名空间")
parser.add_argument("--dry-run", action="store_true", help="只显示不执行")
parser.add_argument("--phase", choices=["Succeeded", "Failed"], help="清理指定状态的 Pod")

args = parser.parse_args()
print(f"命名空间: {args.namespace}")
print(f"试运行: {args.dry_run}")
bash
# 使用方式
python cleanup.py -n production --dry-run --phase Failed

logging — 日志记录

python
import logging

# 基本配置
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)

# 使用
logging.debug("调试信息")    # 不会显示(level=INFO)
logging.info("开始部署")     # 2024-01-15 10:30:00 [INFO] 开始部署
logging.warning("磁盘空间不足")
logging.error("连接失败")
logging.critical("服务宕机")

# 写入文件
logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s"
)

csv — CSV 读写

python
import csv

# 读取 CSV
with open("data.csv", encoding="utf-8") as f:
    reader = csv.DictReader(f)  # 每行变成字典
    for row in reader:
        print(row["name"], row["age"])

# 写入 CSV
with open("output.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerow({"name": "张三", "age": 25})

re — 正则表达式

python
import re

# 查找所有匹配
ips = re.findall(r"\d+\.\d+\.\d+\.\d+", "server 10.0.0.1 and 10.0.0.2")
# ["10.0.0.1", "10.0.0.2"]

# 替换
result = re.sub(r"secret-\w+", "***", "password is secret-abc123")
# "password is ***"

# 分割
parts = re.split(r"[,;]", "a,b;c,d")
# ["a", "b", "c", "d"]

# 验证格式
if re.match(r"^[a-z0-9-]+$", "my-app-name"):
    print("合法的 K8s 资源名")

sqlite3 — SQLite 数据库

python
import sqlite3

# 连接数据库(文件不存在会自动创建)
conn = sqlite3.connect("app.db")
cursor = conn.cursor()

# 建表
cursor.execute("""
    CREATE TABLE IF NOT EXISTS pods (
        name TEXT PRIMARY KEY,
        namespace TEXT,
        status TEXT
    )
""")

# 插入
cursor.execute("INSERT INTO pods VALUES (?, ?, ?)", ("nginx", "default", "Running"))
conn.commit()

# 查询
cursor.execute("SELECT * FROM pods WHERE namespace = ?", ("default",))
for row in cursor.fetchall():
    print(row)

conn.close()

http.server — 简易 HTTP 服务器

python
# 命令行一行启动(快速共享文件)
# python -m http.server 8080

# 代码中自定义处理
from http.server import HTTPServer, SimpleHTTPRequestHandler

class MyHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(b'{"status": "ok"}')

server = HTTPServer(("0.0.0.0", 8080), MyHandler)
server.serve_forever()

datetime — 日期时间

python
from datetime import datetime, timedelta

# 当前时间
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # 2024-01-15 10:30:00

# 时间计算
yesterday = now - timedelta(days=1)
tomorrow = now + timedelta(hours=24)

# 解析时间字符串
dt = datetime.strptime("2024-01-15", "%Y-%m-%d")

# 时间差
diff = now - dt
print(diff.days)

常用第三方库速查

用途推荐库
HTTP 请求httpx, requests
配置管理python-decouple, pydantic-settings
数据校验pydantic
CLI 工具click, typer
日志loguru
测试pytest
代码格式化ruff
类型检查mypy

学习资源

基于 MIT 许可发布