编程笔记
码集 · 笔记 / 速查 / 摘录

目录索引

以下为站内全部记录的分类索引。点击标题可跳转至对应内容。

按分类

Git · 2 Python · 4 Linux · 3 网络 · 1 工具 · 2 入门 · 3 进阶 · 4 速查 · 5

全部记录(12 条)

  1. Git 常用命令速记 入门Git
  2. Git 进阶:rebase 与 cherry-pick 的取舍 进阶Git
  3. Python 数据结构:列表/字典/集合 入门Python
  4. Python 推导式与生成器:从列表到惰性求值 进阶Python
  5. Python 文件与异常:从 with open 到 JSON 入门Python
  6. Python 实用脚本片段 进阶Python
  7. Linux 服务管理与日志 Linux速查
  8. Linux 排查三板斧:top / iotop / strace 进阶Linux
  9. curl 常用模板:从测速到调 API 速查网络
  10. SSH 密钥认证与跳板配置 速查Linux
  11. Docker 入门速记:镜像、容器、Compose 工具入门
  12. 正则表达式速查:元字符 + Python re 示例 速查Python

系统笔记(12)

1. Git 常用命令速记入门 · Git

日常开发的高频 Git 命令,从初始化到回滚一站全收。

# 初始化与克隆
git init
git clone <url>

# 暂存与提交
git status
git add .                  # 暂存所有
git add path/to/file       # 暂存单个文件
git commit -m "msg"        # 提交
git commit --amend         # 修改最近一次提交

# 分支
git branch -a              # 列出所有分支
git checkout -b feat/x     # 新建并切换
git checkout main          # 切回主分支
git merge feat/x           # 合并分支
git branch -d feat/x       # 删除已合并分支

# 远程
git remote add origin <url>
git push origin main
git pull --rebase          # 拉取并变基

# 撤销
git reset --soft HEAD~1    # 撤销最近一次 commit,保留改动
git reset --hard HEAD~1    # 撤销最近一次 commit,丢弃改动
git checkout -- file       # 丢弃工作区修改

# 查看
git log --oneline --graph --all
git diff
git show HEAD
小贴士改写历史(push -f)只在个人分支用,共享分支慎用。

2. Git 进阶:rebase 与 cherry-pick 的取舍进阶 · Git

把零碎提交整理成线、把重要提交搬到别的分支——两种"移动提交"的姿势,场景不同选择不同。

rebase:把当前分支"接"到另一个分支的顶端

git checkout feat/x
git rebase main        # feat/x 的提交会在 main 之上重放
git rebase -i HEAD~3   # 交互式 rebase,合并/重写/删除最近 3 个提交

适用:合并前先 rebase 一次,得到一条干净的直线;在交互式 rebase 里 squash 多次"WIP"提交。

cherry-pick:从任意分支挑单个/多个提交

git checkout main
git cherry-pick <commit-sha>        # 单个
git cherry-pick A..B                 # 区间(A 不包含)
git cherry-pick -n <commit-sha>     # 不自动 commit,先 --no-commit

适用:hotfix 从 main 提到 release,或者把某次提交从老分支"搬"到新分支。

取舍rebase 改写历史,不要在已推送的共享分支上做;cherry-pick 不改写源分支历史,更安全但会产生重复提交。

3. Python 数据结构:列表/字典/集合入门 · Python

列表有序可重复、字典键值映射、集合去重——三个最常用容器的常见操作。

# 列表 list
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.append(7)            # 追加
nums.extend([8, 10])      # 拼接
nums.insert(0, 0)         # 插入
nums.remove(1)            # 删第一个匹配值
nums.pop()                # 弹最后一个
nums.sort()               # 原地排序
nums.sort(reverse=True)   # 降序
sorted(nums)              # 返回新列表
nums.reverse()

# 字典 dict
d = {"name": "tom", "age": 20}
d["email"] = "t@x.com"
d.get("phone", "N/A")     # 安全取值
d.setdefault("city", "BJ")
d.update({"age": 21, "city": "SH"})
d.pop("email")
d.keys(); d.values(); d.items()

# 集合 set(去重 + 集合运算)
s = {1, 2, 3}
s.add(4); s.discard(2)
a & b   # 交集
a | b   # 并集
a - b   # 差集
a ^ b   # 对称差

4. Python 推导式与生成器:从列表到惰性求值进阶 · Python

一行的优雅,百倍内存的差距——什么时候用 []、什么时候用 ()。

# 列表推导式(立即生成完整列表)
squares = [x*x for x in range(10)]
evens   = [x for x in range(20) if x % 2 == 0]
pairs   = [(x, y) for x in range(3) for y in range(3)]

# 字典推导式
square_map = {x: x*x for x in range(5)}

# 集合推导式
unique = {x % 5 for x in range(20)}

# 生成器表达式(惰性,内存友好)
gen = (x*x for x in range(10**8))   # 不占内存
next(gen)                            # 0
sum(x*x for x in range(10**8))       # sum 直接吃生成器

# yield 函数(可复用的生成器)
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b
list(fib(10))  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
小贴士数据量大(>10万)优先用生成器;需要反复遍历或取 len()/索引 才用列表。

5. Python 文件与异常:从 with open 到 JSON入门 · Python

正确地打开文件、捕获异常、读写 JSON,Python IO 入门三件套。

# 文本读写(总用 with)
with open("data.txt", encoding="utf-8") as f:
    content = f.read()             # 一次性
    f.seek(0)
    for line in f:                 # 逐行
        print(line.rstrip())

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

# 异常处理
try:
    n = int(s)
except ValueError as e:
    print("不是整数:", e)
except Exception as e:
    print("其它异常:", e)
else:
    print("成功,n =", n)
finally:
    print("总会跑")

# JSON
import json
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

6. Python 实用脚本片段进阶 · Python

日常工作里反复会用到的小工具,每个都标了"用途 / 代码 / 说明"。

6.1 批量改后缀

import os
for name in os.listdir("."):
    if name.endswith(".txt"):
        os.rename(name, name[:-4] + ".md")

6.2 端口探活

import socket
s = socket.socket()
s.settimeout(2)
try:
    s.connect(("127.0.0.1", 3306))
    print("OK")
except Exception as e:
    print("FAIL", e)
finally:
    s.close()

6.3 日志抓错行

import re
pat = re.compile(r"\d{4}-\d{2}-\d{2}.*ERROR.*")
with open("app.log", encoding="utf-8") as f:
    for line in f:
        if pat.search(line):
            print(line.rstrip())

6.4 命令行进度条

import sys, time
for i in range(1, 101):
    sys.stdout.write(f"\r{i:3d}% |{'█'*i}{' '*(100-i)}|")
    sys.stdout.flush()
    time.sleep(0.05)
print()

7. Linux 服务管理与日志Linux · 速查

systemd 体系下的服务启停、日志查看、开机自启。

systemctl status nginx          # 状态
systemctl start nginx           # 启动
systemctl stop nginx            # 停止
systemctl restart nginx         # 重启
systemctl reload nginx          # 平滑重载(不丢连接)
systemctl enable nginx          # 开机自启
systemctl disable nginx         # 取消开机自启

# 日志
journalctl -u nginx             # 单元日志
journalctl -u nginx -f          # 实时跟踪
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b            # 启动以来的错误
journalctl --vacuum-time=7d     # 清理 7 天前的

8. Linux 排查三板斧:top / iotop / strace进阶 · Linux

系统变慢、磁盘狂转、调用卡住——这三板斧能解决八成日常故障。

① top / htop — 看进程 CPU / 内存

top                # 系统自带
htop               # 更直观,需安装
# 常用交互: P 按 CPU 排序, M 按内存排序, 1 展开各核
# 看到某进程 %CPU 高,记下 PID

② iotop — 看谁在狂 IO

sudo iotop -o     # 只看正在 IO 的进程
sudo iotop -P      # 只显示进程,不显示线程
# 常见:MySQL 写盘、Nginx 写日志、备份脚本

③ strace — 看进程在做什么系统调用

strace -p <PID>                 # 跟踪已有进程
strace -p <PID> -e trace=network,file
strace -c -p <PID>              # 汇总:每种系统调用耗时/次数
# 看到卡在 read() 上 → 磁盘 IO;卡在 connect() → 网络;卡在 futex → 锁
组合拳先 top 看 CPU/内存 → iotop 看 IO → strace 追系统调用,基本能定位到根因。

9. curl 常用模板:从测速到调 API速查 · 网络

# 1) 只看响应头
curl -I https://example.com

# 2) 跟随重定向 + 输出状态码
curl -L -o /dev/null -s -w '%{http_code} %{url_effective}\n' https://bit.ly/xxx

# 3) 下载到文件
curl -o file.zip https://x/y.zip
curl -O https://x/y.zip                    # 用服务器文件名

# 4) POST 表单
curl -X POST -d "a=1&b=2" https://api.example.com/login

# 5) POST JSON
curl -X POST -H "Content-Type: application/json" \
     -d '{"name":"tom","age":20}' https://api.example.com/users

# 6) 带鉴权
curl -u user:pass https://api.example.com
curl -H "Authorization: Bearer xxx" https://api.example.com

# 7) 上传文件
curl -F "file=@/path/to/local" https://api.example.com/upload

# 8) 测速
curl -o /dev/null -s -w '%{time_total}s  %{speed_download} B/s\n' https://x/big.iso

# 9) 超时
curl --max-time 10 --connect-timeout 5 https://x

10. SSH 密钥认证与跳板配置速查 · Linux

免去每次输密码、用 config 一键连多台机器、用跳板穿内网。

# 1) 生成密钥对
ssh-keygen -t ed25519 -C "me@host"

# 2) 把公钥推到远端
ssh-copy-id user@host

# 3) 配置文件 ~/.ssh/config
# Host 别名
#   HostName 真实 IP/域名
#   User 用户名
#   Port 端口
#   IdentityFile ~/.ssh/id_ed25519
cat >> ~/.ssh/config <<'EOF'
Host myhost
  HostName 1.2.3.4
  User root
  Port 22

Host inner
  HostName 10.0.0.5
  User app
  ProxyCommand ssh -W %h:%p myhost
EOF

# 4) 跳板
ssh inner                    # 实际是 ssh 10.0.0.5 via myhost

# 5) 端口转发(本地)
ssh -L 8080:localhost:80 myhost    # 访问本机 8080 = 远端 80
ssh -D 1080 myhost                  # 动态 SOCKS 代理

# 6) 传文件
scp file.tar myhost:/tmp/
rsync -avz ./dir/ myhost:/path/

11. Docker 入门速记:镜像、容器、Compose工具 · 入门

# 镜像
docker pull nginx:latest
docker images
docker rmi nginx:old
docker image prune -a             # 清理无用镜像

# 容器(单次)
docker run -d -p 80:80 --name web nginx
docker ps                        # 在运行
docker ps -a                     # 全部
docker logs -f web               # 实时日志
docker exec -it web sh           # 进 shell
docker stop web
docker start web
docker rm -f web

# Compose(多服务)
cat > docker-compose.yml <<'YAML'
version: "3.9"
services:
  web:
    image: nginx
    ports: ["80:80"]
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: 123456
YAML

docker compose up -d
docker compose down
docker compose logs -f web

# 清理
docker system df                 # 看占用
docker system prune -a --volumes

12. 正则表达式速查:元字符 + Python re 示例速查 · Python

# 元字符
.       任意单字符(不含换行)
^       开头
$       结尾
*       0 次或多次
+       1 次或多次
?       0 次或 1 次
{n,m}   n~m 次
[]      字符集, [^] 取反
|       或
()      分组 (?:) 非捕获
\d      数字  \D  非数字
\w      字母数字下划线  \W
\s      空白  \S
\b      单词边界

# Python re
import re

re.match(r"^\d+$", s)         # 匹配开头
re.search(r"\d+", s)          # 找第一个
re.findall(r"\d+", s)         # 找所有(返回列表)
re.sub(r"\s+", " ", s)        # 替换
re.split(r"[,;]", s)          # 分割
re.compile(r"...").findall(s) # 预编译,反复使用更快

# 常用模板
# 邮箱(简化)
r"^[\w.+-]+@[\w-]+\.[\w.-]+$"
# IPv4
r"^(?:\d{1,3}\.){3}\d{1,3}$"
# URL(简化)
r"https?://[\w.-]+(?:/[\w./?=&%-]*)?"
# 日期 yyyy-mm-dd
r"^\d{4}-\d{2}-\d{2}$"

速查(8 张)

把最常用、但又最容易被忘的命令集中起来。点击展开。

① Git 速查
git init                     # 初始化仓库
git clone <url>              # 克隆
git status                   # 查看状态
git add .                    # 暂存所有
git commit -m "msg"          # 提交
git push origin main         # 推送
git pull --rebase            # 拉取并变基
git branch -a                # 所有分支
git checkout -b feat/x       # 新建并切换
git merge feat/x             # 合并分支
git rebase main              # 把当前分支接到 main 上
git stash / git stash pop    # 暂存/恢复
git log --oneline --graph    # 图形化日志
git reset --soft HEAD~1      # 撤销最近一次 commit,保留改动
② Python 速查
# 类型
int(x)  float(x)  str(x)  bool(x)  list(x)  tuple(x)  set(x)  dict(x)

# 序列操作
a[1:3]  a[:5]  a[::-1]  a[::2]
len(a)  min(a)  max(a)  sum(a)  sorted(a)  reversed(a)
a.append(x)  a.extend(b)  a.insert(i,x)  a.remove(x)  a.pop()  a.clear()

# 字典
d.get(k, default)  d.setdefault(k, v)
d.keys()  d.values()  d.items()
{k: v for k, v in iterable}

# 字符串
s.split(sep)  sep.join(seq)  s.strip()  s.replace(a, b)
f"hello {name}"  s.startswith(p)  s.endswith(p)  s.find(sub)

# 文件
with open("f.txt", encoding="utf-8") as f:
    data = f.read()
for line in open("f.txt", encoding="utf-8"):
    ...
③ Linux 常用命令
ls -la                  # 详细列表
cd -                    # 回到上次的目录
pwd                     # 当前路径
mkdir -p a/b/c          # 递归创建
rm -rf dir              # 强制删除
cp -r src dst           # 递归复制
mv a b                  # 改名/移动
chmod 755 file          # rwxr-xr-x
chown user:group file   # 改属主
find . -name "*.log"    # 查找文件
grep -rn "kw" .         # 递归搜索
ps aux | grep nginx     # 查进程
kill -9 PID             # 强杀
top / htop              # 实时资源
df -h                   # 磁盘占用
du -sh dir              # 目录大小
free -h                 # 内存
uname -a                # 内核信息
uptime                  # 运行时长
date                    # 当前时间
④ Docker 速查
docker pull nginx:latest
docker images
docker run -d -p 80:80 --name web nginx
docker ps / docker ps -a
docker logs -f web
docker exec -it web sh
docker stop web  &&  docker start web
docker rm web  &&  docker rmi nginx

# Compose
docker compose up -d
docker compose down
docker compose logs -f

# 清理
docker system prune -a
docker volume ls
docker network ls
⑤ curl 速查
curl -I https://example.com            # 仅看响应头
curl -L https://bit.ly/xxx             # 跟随重定向
curl -o file.zip https://x/y.zip       # 下载到文件
curl -O https://x/y.zip                # 用服务器文件名
curl -X POST -d "a=1&b=2" url          # 表单 POST
curl -H "Authorization: Bearer xxx" url
curl -u user:pass ftp://x/             # FTP
curl --max-time 10 url                 # 超时 10s
curl -w "%{http_code} %{time_total}\n" -o /dev/null -s url  # 测速
⑥ 正则速查
.       任意单字符(不含换行)
^       开头
$       结尾
*       0 次或多次
+       1 次或多次
?       0 次或 1 次
{n,m}   n~m 次
[]      字符集 [^] 取反
|       或
()      分组
\d      数字  \D  非数字
\w      字母数字下划线  \W
\s      空白  \S
\b      单词边界

# Python 用法
import re
re.match(r"^\d+$", s)        # 匹配开头
re.search(r"\d+", s)         # 找第一个
re.findall(r"\d+", s)        # 找所有
re.sub(r"\s+", " ", s)       # 替换
re.split(r"[,;]", s)         # 分割
⑦ SQL 速查
SELECT id, name FROM users WHERE age > 18 ORDER BY id DESC LIMIT 10;

INSERT INTO users(name, age) VALUES ('tom', 20);

UPDATE users SET age = age + 1 WHERE id = 1;

DELETE FROM logs WHERE created_at < '2025-01-01';

-- 聚合
SELECT status, COUNT(*) FROM orders GROUP BY status HAVING COUNT(*) > 5;

-- 连接
SELECT u.name, o.total
FROM users u JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2025-06-01';

-- 索引
CREATE INDEX idx_users_email ON users(email);
⑧ SSH 速查
# 密钥认证
ssh-keygen -t ed25519
ssh-copy-id user@host

# 配置文件 ~/.ssh/config
Host myhost
  HostName 1.2.3.4
  User root
  Port 22
  IdentityFile ~/.ssh/id_ed25519

# 跳板
Host jump
  HostName jump.example.com
  User ubuntu

Host inner
  HostName 10.0.0.5
  User app
  ProxyCommand ssh -W %h:%p jump

# 常用
ssh -p 2222 user@host
ssh -L 8080:localhost:80 user@host   # 本地转发
ssh -D 1080 user@host                 # 动态 SOCKS 代理
scp file user@host:/path/             # 传文件

摘录(15 段)

独立可复用的代码片段,每段都标了"用途 / 代码 / 说明",可直接复制使用。

片段 1:批量重命名文件

用途:把目录下所有 .txt 改成 .md

import os
for name in os.listdir("."):
    if name.endswith(".txt"):
        os.rename(name, name[:-4] + ".md")

说明:os.listdir 列出当前目录,endswith 过滤后改后缀。

片段 2:检测端口是否通

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
    s.connect(("127.0.0.1", 3306))
    print("OK")
except Exception as e:
    print("FAIL", e)
finally:
    s.close()

说明:用 socket TCP 连接测试端口,比 telnet 干净。

片段 3:从日志中抓错误行

import re
pat = re.compile(r"\d{4}-\d{2}-\d{2}.*ERROR.*")
with open("app.log", encoding="utf-8") as f:
    for line in f:
        if pat.search(line):
            print(line.rstrip())

说明:正则匹配"日期+ERROR"行,逐行处理避免一次性读入大文件。

片段 4:JSON 文件读写

import json
# 读
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)
# 写
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

说明:ensure_ascii=False 让中文不被转义,indent=2 让输出可读。

片段 5:命令行进度条

import sys, time
for i in range(1, 101):
    sys.stdout.write(f"\r{i:3d}% |{'█'*i}{' '*(100-i)}|")
    sys.stdout.flush()
    time.sleep(0.05)
print()

说明:\r 让光标回到行首,flush 立刻输出,适合小工具。

片段 6:一键健康检查

#!/bin/bash
echo "--- 磁盘 ---"; df -h | head -3
echo "--- 内存 ---"; free -h | head -2
echo "--- 负载 ---"; uptime
echo "--- 服务 ---"; ss -tlnp | head -10

说明:小脚本粘到 /usr/local/bin/health,加执行权限就能用。

片段 7:取两个文件的差集

comm -23 <(sort a.txt) <(sort b.txt)

说明:comm -23 取只在 a 中出现的行;先 sort 是必需的。

片段 8:统计 Nginx 日志 TOP IP

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head 10

说明:awk 切第一列(客户端 IP),逐层聚合取 Top10。

片段 9:把当前目录打成 tar.gz

tar czf ../backup-$(date +%Y%m%d).tar.gz .

说明:$(date +%Y%m%d) 让文件名带日期,避免覆盖。

片段 10:查看谁占用了 80 端口

ss -tlnp | grep ':80 ' || lsof -i :80

说明:两个工具任选其一,都看不到时可加 sudo。

片段 11:Python 简易 HTTP 服务

python3 -m http.server 8000

说明:一行命令把当前目录变成 http://localhost:8000 静态站点,常用于临时分享文件。

片段 12:用 dd 写 ISO 到 U 盘

sudo dd if=debian.iso of=/dev/sdX bs=4M status=progress oflag=sync

说明:注意 of= 是设备(/dev/sdX)不是分区;写错会清空硬盘。

片段 13:Python 时间戳 ↔ 字符串

from datetime import datetime
ts = int(datetime.now().timestamp())
s = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")

说明:timestamp() 转秒,strftime 格式化为字符串。

片段 14:取 CPU 核心数

import os, multiprocessing
print("亲和:", len(os.sched_getaffinity(0)))
print("逻辑:", multiprocessing.cpu_count())

说明:容器里 prefer sched_getaffinity,反映真正可用的核数。

片段 15:shell 多行 grep

grep -A 3 -B 1 "ERROR" app.log

说明:-A 3 后 3 行,-B 1 前 1 行,看上下文特别有用。