Python:一日速通
Python的特点:简洁、自由、信任程序员
有过Java、JS开发经验的再学习Python 会觉得很容易上手,这也是Python一日速通的前提。
Python :速通项目
速通项目(涵盖所有常用语法),Python 3.9 及以上可以直接跑。
basics.py:语法速览,直接运行,按顺序打印各种示例。dupfind.py:一个小实战,扫描目录,找出内容完全相同的文件。README.md:这份说明。
知识点清单
数据结构与语法
1. 字符串常用方法 `strip` / `lower` / `replace` / `join`(`basics.py:47-50`)
2. 字符串不可变,方法都返回新字符串(`basics.py:47`)
3. 列表 `append` / `insert` / `sort`(`basics.py:52-57`)
4. 切片:左闭右开、负步长反转(`basics.py:58`)
5. `sort` 原地排序与 `sorted` 返回新列表的区别(`basics.py:57-59`)
6. 变量别名与浅拷贝 `a.copy()`(`basics.py:61-67`)
7. 元组、元组解包(`basics.py:69-73`)
8. 字典增改、`get` 默认值、`items()` 遍历、插入顺序、`max(key=...)`(`basics.py:75-79`)
9. 集合去重、并集/交集/差集(`basics.py:81-83`)
10. 列表推导式、字典推导式(`basics.py:85-87`)
11. 自定义排序 `key`(`basics.py:89-91`)
12. `Counter.most_common`、`defaultdict(list)` 分组(`basics.py:93-100`)
13. f-string:`!r`、精度格式化(`basics.py:23,72,133`)
14. 函数是一等对象:放进列表再依次调用(`basics.py:298-306`)
函数与闭包
15. 函数默认参数(`Timer`、`Account`、`SavingsAccount`)
16. `*args` / `**kwargs`(装饰器的 `wrapper`)
17. 闭包:内层函数记住外层变量(`basics.py:171-181`)
18. `nonlocal` 修改外层变量(`basics.py:176,285`)
19. 装饰器、`functools.wraps` 保留原函数信息(`basics.py:183-200`)
20. 匿名函数 `lambda` 的 4 处用法(`basics.py:91`;`dupfind.py:84,99,136`)
面向对象
21. `class`、`__init__`、`self`、实例属性(`basics.py:103-110`)
22. 类属性 `bank`,实例和类都能访问(`basics.py:106`)
23. 下划线开头的私有约定 `_balance`(`basics.py:110`)
24. `@property` 只读属性(`basics.py:112-116`)
25. `@classmethod` 备选构造方式 `empty()`(`basics.py:122-125`)
26. `@staticmethod` 工具方法 `valid_amount()`(`basics.py:127-130`)
27. `__repr__` 自定义对象的打印形式(`basics.py:132`)
28. 继承与 `super().__init__()`(`basics.py:136-142`)
29. `isinstance` 判断实例类型(`basics.py:164`)
30. `@dataclass` 自动生成 `__init__` / `__repr__` / `__eq__`(`basics.py:145`)
31. 魔术方法:`__enter__` / `__exit__`(`basics.py:29-44`)
异常
32. `raise` 主动抛异常(`basics.py:210-215`)
33. 自定义异常继承体系 `ShopError -> OutOfStock`(`basics.py:202-207`)
34. `try / except / else / finally` 的执行顺序(`basics.py:219-232`)
35. 多个 `except` 的顺序,用基类捕获子类(`basics.py:224-228`)
36. `raise ... from ...` 异常链与 `__cause__`(`basics.py:236-241`)
37. 内置异常 `ValueError` 的捕获与转换(`basics.py:237-239`)
38. `with` 上下文管理器(`basics.py:244`)
39. `OSError` 兜底:读失败的文件跳过或记录,不中断整体(`dupfind.py:60-62,96-104`)
模块与包
40. 模块导入:`from basics import Timer, human_size`(`dupfind.py:25`)
41. `__name__` 与 `if __name__ == "__main__":`(`basics.py:313`;`dupfind.py:185-186`)
42. 包的概念:`__init__.py`、`python -m 包名.模块`(见下文「关于模块和包」,代码没有实际建包)
43. `argparse`:位置参数、默认值、`--min-size`(`dupfind.py:161-170`)
44. 标准库使用:`hashlib`、`os`、`sys`、`pathlib`、`collections`、`concurrent.futures`、`dataclasses`、`functools`、`threading`、`time`
多线程与多进程
45. GIL,以及 I/O 密集型与 CPU 密集型的选型(`basics.py:261-262`)
46. 串行与并行计时对比(`basics.py:265-276`)
47. `ThreadPoolExecutor` 与 `pool.map`(`basics.py:267-269`)
48. `ProcessPoolExecutor` 与顶层可序列化的 worker(`basics.py:274-276`;`dupfind.py:89,119-120`)
49. `threading.Thread` 的 `start()` / `join()`(`basics.py:288-294`)
50. `threading.Lock` 配合 `with` 保护共享计数(`basics.py:282-295`)
51. 进程启动有开销,任务太小时并行不一定更快(`basics.py:278`)
实战项目中的用法
52. `os.walk` 遍历,原地修改 `dirnames` 剪枝(`dupfind.py:52-58`)
53. `pathlib` 的 `iterdir` / `stat` / `is_file` / `is_dir`(`dupfind.py:67-86`)
54. 闭包作为过滤谓词 `make_skipper()`(`dupfind.py:38-49`)
55. 按文件大小预筛重复候选(`dupfind.py:106-113`)
56. sha256 分块读取大文件(`dupfind.py:89-104`)
57. `defaultdict` + `(size, digest)` 复合键分组(`dupfind.py:122-133`)
58. 按可释放空间排序(`dupfind.py:136-137`)
59. `@dataclass Report` 组织结果(`dupfind.py:31-35`)
60. 错误收集、只展示前 3 条(`dupfind.py:147-156`)
61. `--min-size` 过滤空文件和过小文件(`dupfind.py:106-110,163-167`)
62. `human_size` 字节数换算(`basics.py:18-25`)
63. `sys.stderr` 与退出码 `SystemExit`(`dupfind.py:173-186`)
关于模块和包
- 一个 `.py` 文件就是一个模块。`dupfind.py` 里的 `from basics import Timer, human_size` 就是在使用另一个模块。
- 模块被 import 时,`__name__` 是模块名;直接运行时是 `"__main__"`。所以 `basics.py` 的示例只在 `python3 basics.py` 时执行,被 import 时不会乱打印。
- 包是带 `__init__.py` 的目录,目录名就是包名,可以用 `python3 -m 包名.模块` 运行。这个项目只有两个文件,不建包更清楚;等代码拆到子目录时再建。
运行
python3 basics.py
python3 dupfind.py .
dupfind.py 的用法:
python3 dupfind.py [目录] [--min-size 字节数]
可以在项目目录里复制一份 README 制造重复case:
cp README.md README-copy.md
python3 dupfind.py .
rm README-copy.md
输出大致是这样:
扫描 耗时 0.001s
目录:/Users/you/python-beginner
文件:4 个
重复:1 组,可释放 7.1 KB
[1] 7.1 KB x 2,sha256=...
README-copy.md
README.md
重复文件是怎么找的
- 先按文件大小分组。大小只出现一次的文件不可能重复,直接排除,能省掉大部分哈希计算。
- 对剩下的文件算 sha256。这是 CPU 密集型工作,用
ProcessPoolExecutor分给多个进程。 - 按
(大小, sha256)分组,组里多于一个文件的就是重复。
目录遍历主要是在等磁盘,所以 collect_files() 用线程池按子目录并行。线程受 GIL 限制,计算任务用进程才可能真正并行;任务很小时,进程启动开销也可能吃掉收益。
--min-size 默认是 1,空文件不参与比较;想看空文件是否重复可以传 --min-size 0。扫描时默认跳过 .git、__pycache__、.venv 这些目录,规则在 SKIP_DIRS 里。
代码demo
一、基础语法 basics.py
"""Python 语法速览,边跑边看。
python basics.py
按“数据结构 -> 面向对象 -> 闭包 -> 异常 -> 线程/进程”排了几个函数,
直接运行会依次执行。另外这里放了两个小工具 Timer 和 human_size,
dupfind.py 会 import 它们,这也是最朴素的模块用法。
"""
import functools
import threading
import time
from collections import Counter, defaultdict
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass
def human_size(size):
"""把字节数换成 KB/MB 这种好读的形式。"""
size = float(size)
for unit in ("B", "KB", "MB", "GB"):
if size < 1024:
# 字节不需要小数,更大的单位保留一位
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} TB"
class Timer:
"""with Timer("扫描"): ... 结束时打印耗时。"""
def __init__(self, label=""):
self.label = label
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc, tb):
self.elapsed = time.perf_counter() - self.start
label = f"{self.label} 耗时" if self.label else "耗时"
print(f"{label} {self.elapsed:.3f}s")
return False # 返回 False,异常照常往外抛
def data_structures():
# 字符串不可变,strip/lower/replace 都是返回新字符串
raw = " Hello, Python "
print(repr(raw.strip()))
print(raw.strip().lower().replace("python", "新世界"))
print(", ".join(["a", "b", "c"])) # join 只收字符串,数字要先 str()
# 列表:最常用的容器
nums = [3, 1, 2]
nums.append(4)
nums.insert(0, 0)
nums.sort() # 原地排序,返回 None
print(nums, nums[1:3], nums[::-1]) # 切片左闭右开;负步长是反转
print(sorted(nums, reverse=True)) # sorted 不改原列表
# 变量名只是引用,b = a 不会复制列表
a = [1, [2, 3]]
b = a
c = a.copy() # 浅拷贝,里层列表还是共享的
a[1].append(4)
print("b:", b, "c:", c)
# 元组不可变,适合当一组固定的记录,也可以做字典的 key
point = (3, 5)
x, y = point # 解包
print(f"({x}, {y}) 到原点 {(x ** 2 + y ** 2) ** 0.5:.2f}")
# 字典按 key 查找,3.7 之后会保留插入顺序
scores = {"语文": 90, "数学": 95}
scores["英语"] = 88
print(scores.get("物理", 0)) # 取不到时给默认值,不会抛 KeyError
for subject, score in scores.items():
print(subject, score)
print("最高分:", max(scores, key=scores.get))
# 集合:去重、交并差,判断“有没有”很快
tags = {"python", "go", "python"}
print(sorted(tags), sorted(tags | {"rust"}), sorted(tags & {"python", "rust"}))
# 推导式:从一个序列快速造出另一个
print([n * n for n in range(6) if n % 2])
print({name: len(name) for name in ["py", "python"]})
# sorted 的 key 决定按什么排
people = [("小明", 90), ("小红", 95), ("小刚", 88)]
print(sorted(people, key=lambda item: item[1], reverse=True))
# Counter 计数,defaultdict 分组,省掉很多 if key not in ...
words = "the quick brown fox jumps over the lazy dog".split()
print(Counter(words).most_common(2))
grouped = defaultdict(list)
for name, dept in [("小明", "后端"), ("小红", "前端"), ("小刚", "后端")]:
grouped[dept].append(name)
print(dict(grouped))
class Account:
"""一个够用的账户类:类属性、property、类方法都在这里。"""
bank = "示例银行" # 类属性,所有实例共用
def __init__(self, owner, balance=0.0):
self.owner = owner
self._balance = balance # 下划线只是约定,不是真私有
@property
def balance(self):
"""只读属性,访问时不用写括号。"""
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("存款金额必须大于 0")
self._balance += amount
@classmethod
def empty(cls, owner):
"""类方法一般用来提供另一种创建实例的方式。"""
return cls(owner)
@staticmethod
def valid_amount(amount):
"""不依赖 self/cls 的工具函数放静态方法里。"""
return amount > 0
def __repr__(self):
return f"Account({self.owner!r}, balance={self._balance:.2f})"
class SavingsAccount(Account):
def __init__(self, owner, balance=0.0, rate=0.02):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate)
@dataclass
class Point:
"""dataclass 会自动生成 __init__、__repr__、__eq__。"""
x: float
y: float
def distance_to(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
def oop():
account = Account("小明", 100)
account.deposit(50)
print(account, account.balance, Account.bank)
print(Account.empty("小红"), Account.valid_amount(-1))
saving = SavingsAccount("小刚", 1000, rate=0.05)
saving.add_interest()
print(saving, isinstance(saving, Account))
print(Point(0, 0).distance_to(Point(3, 4)))
print(Point(0, 0) == Point(0, 0)) # dataclass 生成的 __eq__
def closures():
def make_counter():
"""闭包:counter 记住了外层的 count,每次 make_counter 都是独立一份。"""
count = 0
def counter():
nonlocal count # 要改外层变量,得声明 nonlocal
count += 1
return count
return counter
c1, c2 = make_counter(), make_counter()
print(c1(), c1(), c1(), c2())
def traced(fn):
"""装饰器就是“收一个函数、返回一个新函数”的闭包。"""
@functools.wraps(fn) # 保住原函数的名字和文档字符串
def wrapper(*args, **kwargs):
print(f"-> {fn.__name__}{args}")
return fn(*args, **kwargs)
return wrapper
@traced
def add(a, b):
return a + b
print(add(1, 2), add.__name__)
class ShopError(Exception):
"""自定义异常的基类,方便上层统一处理。"""
class OutOfStock(ShopError):
pass
def buy(stock, name, count):
if name not in stock:
raise ShopError(f"没有这个商品:{name}")
if count > stock[name]:
raise OutOfStock(f"{name} 库存不足,只剩 {stock[name]} 件")
stock[name] -= count
return count
def exceptions():
stock = {"键盘": 2}
print("买入:", buy(stock, "键盘", 1), "剩余:", stock["键盘"])
try:
buy(stock, "键盘", 5)
except OutOfStock as exc:
print("失败:", exc)
except ShopError as exc:
print("其他商品问题:", exc)
else:
print("下单成功")
finally:
print("不管成不成,finally 都会执行,适合做清理")
# 换掉异常类型时保留原始原因,排查问题方便很多
try:
try:
int("三")
except ValueError as exc:
raise ShopError("数量必须是数字") from exc
except ShopError as exc:
print("转换失败:", exc, "原因:", repr(exc.__cause__))
# 类实现 __enter__ / __exit__ 就能用 with,Timer 也会在 dupfind.py 里用
with Timer("求和"):
sum(range(1_000_000))
def io_job(seconds):
time.sleep(seconds) # 模拟网络或磁盘等待
return f"等了 {seconds}s"
def cpu_job(n):
total = 0
for i in range(n):
total += i * i
return total
def concurrency():
# CPython 有 GIL:同一时刻只有一个线程执行 Python 字节码。
# 线程适合等待型任务,CPU 密集的任务交给进程才可能真正并行。
jobs = [0.1] * 5
with Timer("串行 I/O"):
[io_job(s) for s in jobs]
with Timer("线程池 I/O"):
with ThreadPoolExecutor(max_workers=5) as pool:
list(pool.map(io_job, jobs))
numbers = [2_000_000] * 4
with Timer("串行计算"):
serial = [cpu_job(n) for n in numbers]
with Timer("进程池计算"):
with ProcessPoolExecutor() as pool:
parallel = list(pool.map(cpu_job, numbers))
assert serial == parallel
# 进程启动有开销,任务太小时并行不一定更快
# 线程共享内存,同时改一个变量要加锁,否则可能丢更新
total = 0
lock = threading.Lock()
def add():
nonlocal total
for _ in range(10000):
with lock:
total += 1
threads = [threading.Thread(target=add) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("计数结果:", total)
def main():
sections = [
("数据结构", data_structures),
("面向对象", oop),
("闭包与装饰器", closures),
("异常", exceptions),
("线程与进程", concurrency),
]
for title, fn in sections:
print(f"\n## {title}")
fn()
# 一个 .py 文件就是一个模块:被 import 时 __name__ 是模块名,
# 直接运行时是 "__main__",所以 main() 只在直接运行时执行。
if __name__ == "__main__":
main()
二、速通项目 dupfind.py
"""找出目录中内容完全相同的文件。
用法:
python dupfind.py .
python dupfind.py ~/Downloads --min-size 1024
思路:
1. 按文件大小分组,大小只出现一次的肯定不重复,先排除;
2. 剩下的文件算 sha256,这一步是纯计算,交给进程池;
3. 按 (大小, 哈希) 分组,组里多于一个文件的就是重复。
遍历目录大部分时间在等磁盘,所以按子目录分给线程池。
"""
import argparse
import hashlib
import os
import sys
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
# 同目录下的 basics.py 就是一个模块,直接 import 即可
from basics import Timer, human_size
CHUNK = 1024 * 1024
SKIP_DIRS = {".git", ".idea", "__pycache__", ".venv", "venv", "node_modules"}
@dataclass
class Report:
scanned: int
groups: list # 每项是 (文件大小, sha256, [路径, ...])
errors: list # 每项是 (路径, 错误信息)
def make_skipper(extra=()):
"""返回一个判断“目录要不要跳过”的函数。
用闭包把 names 记在函数里,walk 和 collect 两边直接调用就行。
"""
names = SKIP_DIRS | set(extra)
def skip(name):
return name in names
return skip
def walk_dir(top, skip):
"""递归收集 (Path, 文件大小)。单个文件 stat 失败就跳过。"""
files = []
for dirpath, dirnames, filenames in os.walk(top):
# 原地修改 dirnames,os.walk 就不会进入这些目录
dirnames[:] = [d for d in dirnames if not skip(d)]
for name in filenames:
path = Path(dirpath) / name
try:
files.append((path, path.stat().st_size))
except OSError:
pass
return files
def collect_files(root, skip, workers=8):
"""顶层文件直接收,子目录分给线程池并行遍历。"""
files = []
subdirs = []
for entry in root.iterdir():
if skip(entry.name):
continue
if entry.is_file():
try:
files.append((entry, entry.stat().st_size))
except OSError:
pass
elif entry.is_dir():
subdirs.append(entry)
if subdirs:
with ThreadPoolExecutor(max_workers=min(workers, len(subdirs))) as pool:
for part in pool.map(lambda d: walk_dir(d, skip), subdirs):
files.extend(part)
return files
def hash_file(path):
"""在子进程里算文件的 sha256。
返回 (路径, 哈希或 None, 错误信息或 None)。异常在这里转成返回值,
一个文件读失败不会让整个进程池崩掉。
"""
digest = hashlib.sha256()
try:
with open(path, "rb") as fp:
# 分块读,别把大文件整个塞进内存
for chunk in iter(lambda: fp.read(CHUNK), b""):
digest.update(chunk)
except OSError as exc:
return path, None, str(exc)
return path, digest.hexdigest(), None
def find_duplicates(files, min_size):
by_size = defaultdict(list)
for path, size in files:
if size >= min_size:
by_size[size].append(path)
# 大小唯一的文件不可能有重复,先筛掉能少算很多哈希
candidates = [path for group in by_size.values() if len(group) > 1 for path in group]
if not candidates:
return [], []
size_of = {str(path): size for path, size in files}
with ProcessPoolExecutor() as pool:
results = list(pool.map(hash_file, [str(path) for path in candidates]))
by_content = defaultdict(list)
errors = []
for path, digest, error in results:
if error is not None:
errors.append((path, error))
continue
by_content[(size_of[path], digest)].append(Path(path))
groups = []
for (size, digest), paths in by_content.items():
if len(paths) > 1:
groups.append((size, digest, sorted(paths)))
# 按能释放的空间从多到少排
groups.sort(key=lambda item: item[0] * (len(item[2]) - 1), reverse=True)
return groups, errors
def print_report(root, report):
print(f"\n目录:{root.resolve()}")
print(f"文件:{report.scanned} 个")
if report.groups:
saved = sum(size * (len(paths) - 1) for size, _, paths in report.groups)
print(f"重复:{len(report.groups)} 组,可释放 {human_size(saved)}")
for index, (size, digest, paths) in enumerate(report.groups, 1):
print(f"\n[{index}] {human_size(size)} x {len(paths)},sha256={digest[:12]}")
for path in paths:
print(f" {path}")
else:
print("没有发现重复文件")
if report.errors:
print(f"\n{len(report.errors)} 个文件读取失败")
for path, error in report.errors[:3]:
print(f" {path}: {error}")
def main(argv=None):
parser = argparse.ArgumentParser(description="找出内容完全相同的文件")
parser.add_argument("path", nargs="?", default=".", help="扫描目录,默认当前目录")
parser.add_argument(
"--min-size",
type=int,
default=1,
help="只比较不小于这个字节数的文件(默认 1,空文件不参与)",
)
args = parser.parse_args(argv)
root = Path(args.path)
if not root.is_dir():
print(f"不是目录:{root}", file=sys.stderr)
return 1
skip = make_skipper()
with Timer("扫描"):
files = collect_files(root, skip)
groups, errors = find_duplicates(files, args.min_size)
print_report(root, Report(len(files), groups, errors))
return 0
if __name__ == "__main__":
raise SystemExit(main())