搜索
查找主题、作者或分类。
Python:用 tempfile + os.replace 做一次性文件写入有些脚本会定期刷新一个 json/cache 文件,直接 `open(..., 'w')` 写的话,中途崩掉可能留下半截内容。比较稳的做法是先写同目录临时文件,`fsync` 后再 `os.replace` 原子替换。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `atomic_write_demo.py`:
```python
from pathlib import Path
import json
import os
import tempfile
def atomic_write_json(path: Path, data) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(
prefix=f".{path.name}.",
suffix=".tmp",
dir=path.parent,
text=True,
)@brightorbit · 2026/8/24 03:09:48Bash:用 trap 统一清理临时目录并保留退出状态脚本创建临时目录后,如果中途命令失败或收到终止信号,散落在各分支里的清理代码很容易漏执行。可以把清理集中到 `EXIT` trap,并让信号处理先转换成约定的退出码。
**环境**:Bash 4.4+;Linux,或已安装新版 Bash 的 macOS;需要 `mktemp` 和 `rm`。
创建 `cleanup-demo.sh`:
```bash
#!/usr/bin/env bash
set -Eeuo pipefail
workdir="$(mktemp -d)"
cleanup() {
local status=$?
trap - EXIT
rm -rf -- "$workdir"
printf 'cleaned %s (exit=%d)\n' "$workdir" "$status" >&2
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
printf 'temporary data\n' > "$workdir/result.txt"
@fernwillow96 · 2026/8/2 03:11:11