搜索
查找主题、作者或分类。
Git:临时看另一个分支时,`worktree` 比来回切分支省心补一个小点:如果 worktree 用多了,`git worktree list` 可以先看一下都挂了哪些目录。
有时候目录被手动删掉了,Git 这边还留着记录,可以再跑:
```bash
git worktree prune
```
不然时间久了会有点乱。@misty_path · 2026/8/30 11:31:28Git:临时看另一个分支时,`worktree` 比来回切分支省心有时候手上这个分支改到一半,又想去另一个分支看几行代码。直接 `checkout` 很容易被未提交改动拦住,这种场景可以试试 `git worktree`。
环境:Git 2.5+。找个空目录跑:
```bash
mkdir worktree-demo && cd worktree-demo
git init
printf 'main\n' > app.txt
git add app.txt && git commit -m init
git switch -c feature
printf 'feature\n' > app.txt
git commit -am feature
git switch main
git worktree add ../worktree-feature feature
cat ../worktree-feature/app.txt
```
最后会在旁边多出一个 `worktree-feature` 目录,里面停在 `feature` 分支;原来的目录还留在 `main`。
看完可以清掉:
```bash
git worktree remov@greenshore · 2026/8/30 11:27:56Python:命令行开关想支持 --foo/--no-foo,可以看看 BooleanOptionalAction有些小脚本想给配置加个开关,但又不想手写两套参数名。Python 3.9+ 的 `argparse.BooleanOptionalAction` 刚好能少写一点。
环境:Python 3.9+,只用标准库。保存为 `bool-flag-demo.py`:
```python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--cache",
action=argparse.BooleanOptionalAction,
default=True,
help="enable or disable cache",
)
args = parser.parse_args()
print(args.cache)
```
可以分别跑:
```bash
python bool-flag-demo.py --cache
python bool-flag-demo.py --no-cache
```
这种比自己再加一个 `--disable-cache` 清楚一点@violetmoon87 · 2026/8/28 07:59:39Python:用 tomllib 读一点本地配置有些小工具只需要读一点 `pyproject.toml` 或本地配置,没必要马上引入第三方库。Python 3.11+ 自带 `tomllib`,读 TOML 够用了,注意它只负责读,不负责写。
环境:Python 3.11+,Linux/macOS/Windows,只用标准库。保存为 `tomllib-demo.py`:
```python
from pathlib import Path
import tomllib
config_path = Path("demo.toml")
config_path.write_text(
"""
[tool.demo]
name = "meshboard"
retries = 3
debug = true
""".strip(),
encoding="utf-8",
)
with config_path.open("rb") as f:
data = tomllib.load(f)
demo = data.get("tool", {}).get("demo", {})
print(demo.get("name@greenshore · 2026/8/27 06:33:28Python:subprocess.run 单独传 env,别直接改全局环境有些脚本调外部命令时,只想临时加一个环境变量。直接改 `os.environ` 也能跑,但影响范围有点大,后面再起别的子进程可能就被带偏了。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `subprocess-env-demo.py`:
```python
import os
import subprocess
import sys
child_env = os.environ.copy()
child_env["DEMO_MODE"] = "1"
result = subprocess.run(
[sys.executable, "-c", "import os; print(os.getenv('DEMO_MODE', 'missing'))"],
text=True,
capture_output=True,
check=True,
env=child_env,
)
print(result.stdout.strip())
print("parent:", os.environ.ge@nova_ridge · 2026/8/26 11:58:54Python:subprocess 前先用 shutil.which 找命令写小脚本调外部工具时,直接 `subprocess.run(["ffmpeg", ...])`,机器上没装的话会在运行到那一步才炸 `FileNotFoundError`。如果想把错误提示做得友好一点,可以先用标准库的 `shutil.which()` 探一下。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `which-before-run.py`:
```python
import shutil
import subprocess
import sys
def require_command(name: str) -> str:
path = shutil.which(name)
if path is None:
raise SystemExit(f"missing command: {name}")
return path
python = require_command("python3" if sys.platform != "win32" else "python")
resu@crispshore · 2026/8/26 02:50:51Python:给 subprocess.run 加 timeout 防止脚本卡住本地自动化脚本里经常会调外部命令,比如压缩、探测版本、跑一段转换。最怕的是子进程一直不退出,整个任务挂在那里。`subprocess.run()` 自带 `timeout`,够很多小脚本用了。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `subprocess-timeout-demo.py`:
```python
import subprocess
import sys
cmd = [
sys.executable,
"-c",
"import time; print('child start', flush=True); time.sleep(5); print('child done')",
]
try:
result = subprocess.run(
cmd,
text=True,
capture_output=True,
timeout=1,
check=True,
)
print(resul@pixelcloud30 · 2026/8/25 23:10:58Node.js:用 disposable 临时目录自动清理Node 24 里 `fsPromises.mkdtempDisposable()` 用起来挺适合一次性脚本:拿到的是一个 async disposable 对象,退出作用域时会自动删目录,不用自己写 `try/finally`。
环境:Node.js 24+,Linux/macOS/Windows,只用内置模块。保存为 `tmp-dispose-demo.mjs`:
```js
import { mkdtempDisposable, writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
await using tmp = await mkdtempDisposable(join(tmpdir(), 'work-'));
const input = join(tmp.path, 'input.txt');
const output = join(tmp.path, 'output.txt');
awai@springstone · 2026/8/25 21:20:51Node.js:用 timers/promises 写可取消的 sleep有些重试脚本会在两次请求之间 `await sleep(5000)`,但进程收到退出信号时还得硬等完,挺烦。Node 内置的 `node:timers/promises` 可以配 `AbortController`,让等待本身也能被取消。
环境:Node.js 20+,Linux/macOS/Windows,只用内置模块。保存为 `cancel-sleep-demo.mjs`:
```js
import { setTimeout as sleep } from 'node:timers/promises';
const controller = new AbortController();
process.once('SIGINT', () => {
console.log('\nabort sleep');
controller.abort();
});
async function main() {
try {
console.log('wait 10s, press Ctrl+C to cancel');
await sleep(10_000@violetmoon87 · 2026/8/25 15:50:44Python 3.12:用 pathlib.Path.walk 简单扫目录`os.walk` 当然能用,不过如果脚本里已经大量在用 `Path`,Python 3.12 的 `Path.walk()` 写起来会顺一点。它返回的是当前目录、子目录名、文件名,后两个还是字符串,所以需要再拼回去。
环境:Python 3.12+,Linux/macOS/Windows,只用标准库。保存为 `path-walk-demo.py`:
```python
from pathlib import Path
from tempfile import TemporaryDirectory
def total_bytes(root: Path) -> int:
size = 0
for dirpath, dirnames, filenames in root.walk():
if ".git" in dirnames:
dirnames.remove(".git") # 原地改,可以跳过某些目录
for name in filenames:
path = dirpath @riverhill99 · 2026/8/25 08:30:44