2.10 Headless Mode(无头模式)
来源: Claude Code 官方文档整理日期: 2025-12-13
概述
Headless Mode(无头模式)是 Claude Code 提供的非交互式运行模式,允许你通过命令行脚本和自动化工具以编程方式运行 Claude Code,无需任何交互式 UI 界面。
简单来说:
- 交互模式:你在终端中与 Claude 对话,一问一答
- 无头模式:程序自动调用 Claude,获取结果后继续执行——适合 CI/CD、自动化脚本、批量处理
基本用法
核心命令是使用 -p(或 --print)标志:
bash
claude -p "Stage my changes and write a set of commits for them" \
--allowedTools "Bash,Read" \
--permission-mode acceptEdits关键点:无头模式不会在会话之间持久化,每次都需要显式触发。
配置选项速查
| 参数 | 说明 | 示例 |
|---|---|---|
--print, -p | 启用非交互模式 | claude -p "query" |
--output-format | 输出格式:text/json/stream-json | claude -p --output-format json |
--resume, -r | 通过会话 ID 恢复对话 | claude --resume abc123 |
--continue, -c | 继续最近的对话 | claude --continue |
--verbose | 启用详细日志(调试用) | claude --verbose |
--append-system-prompt | 追加系统提示词 | claude --append-system-prompt "..." |
--allowedTools | 允许使用的工具列表 | claude --allowedTools Bash,Read |
--disallowedTools | 禁止使用的工具列表 | claude --disallowedTools mcp__github |
--mcp-config | 从 JSON 文件加载 MCP 服务器 | claude --mcp-config servers.json |
--permission-prompt-tool | 权限提示处理工具 | 仅限 --print 模式 |
输出格式详解
1. 文本输出(默认)
bash
claude -p "Explain file src/components/Header.tsx"
# 输出: This is a React component showing...2. JSON 输出
返回结构化数据,包含元信息:
bash
claude -p "How does the data layer work?" --output-format json响应格式:
json
{
"type": "result",
"subtype": "success",
"total_cost_usd": 0.003,
"is_error": false,
"duration_ms": 1234,
"duration_api_ms": 800,
"num_turns": 6,
"result": "The response text here...",
"session_id": "abc123"
}适用场景:需要解析结果、获取成本统计、后续处理
3. 流式 JSON 输出
实时流式传输每条消息:
bash
claude -p "Build an application" --output-format stream-json流程:init 消息 → 用户/助手消息 → result 统计消息
适用场景:实时显示进度、长时间任务监控
输入格式
文本输入
bash
# 直接参数
claude -p "Explain this code"
# 从 stdin
echo "Explain this code" | claude -p流式 JSON 输入(多轮对话)
bash
echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' \
| claude -p --output-format=stream-json --input-format=stream-json --verbose多轮对话管理
bash
# 继续最近的对话
claude --continue "Now refactor this for better performance"
# 通过 session_id 恢复特定对话
claude --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"
# 非交互模式下恢复
claude --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" --no-interactive实战应用场景
场景 1:SRE 事件响应机器人
bash
#!/bin/bash
investigate_incident() {
local incident_description="$1"
local severity="${2:-medium}"
claude -p "Incident: $incident_description (Severity: $severity)" \
--append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \
--output-format json \
--allowedTools "Bash,Read,WebSearch,mcp__datadog" \
--mcp-config monitoring-tools.json
}
# 调用示例
investigate_incident "Payment API returning 500 errors" "high"场景 2:自动化安全审计
bash
audit_pr() {
local pr_number="$1"
gh pr diff "$pr_number" | claude -p \
--append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \
--output-format json \
--allowedTools "Read,Grep,WebSearch"
}
# 审计 PR #123 并保存报告
audit_pr 123 > security-report.json场景 3:多轮法律文档审查
bash
# 启动会话并获取 session_id
session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id')
# 分步骤审查合同
claude -p --resume "$session_id" "Review contract.pdf for liability clauses"
claude -p --resume "$session_id" "Check compliance with GDPR requirements"
claude -p --resume "$session_id" "Generate executive summary of risks"场景 4:批量文件迁移(Fan-out 模式)
这是处理大规模任务的推荐模式:
bash
# 1. 让 Claude 生成任务列表
claude -p "List all files that need migration from framework A to B" \
--output-format json > task_list.json
# 2. 循环处理每个任务
for file in $(jq -r '.files[]' task_list.json); do
claude -p "Migrate $file from framework A to B" \
--allowedTools "Read,Edit,Write" \
--output-format json >> migration_results.json
doneGitHub Actions 集成
快速安装
bash
claude> /install-github-app按提示授权 Claude GitHub App,然后在仓库设置中添加 ANTHROPIC_API_KEY 密钥。
工作流配置示例
yaml
# .github/workflows/claude.yml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Review this PR for code quality and security issues"
claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929"自动化 Issue 分类
Anthropic 官方的 Claude Code 仓库就使用这种模式——当新 Issue 创建时,自动检查并分配标签:
yaml
on:
issues:
types: [opened]
jobs:
triage:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
prompt: "Analyze this issue and assign appropriate labels"最佳实践
1. 使用 JSON 输出便于程序解析
bash
result=$(claude -p "Generate code" --output-format json)
code=$(echo "$result" | jq -r '.result')
cost=$(echo "$result" | jq -r '.total_cost_usd')
echo "Cost: $cost USD"2. 优雅处理错误
bash
if ! claude -p "$prompt" 2>error.log; then
echo "Error occurred:" >&2
cat error.log >&2
exit 1
fi3. 设置超时防止卡死
bash
timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"4. 调试时启用详细日志
bash
# 开发调试
claude -p "..." --verbose
# 生产环境关闭,保持输出干净
claude -p "..."5. 多请求时尊重速率限制
bash
for task in "${tasks[@]}"; do
claude -p "$task" --output-format json
sleep 2 # 添加延迟避免触发限流
done6. CI/CD 性能建议
- 目标延迟:单次审查任务控制在 3-5 分钟内
- 限制轮次:使用
--max-turns避免无限循环 - 质量门禁:AI 修改后仍需通过 build、lint、测试等标准检查
与 SDK 的关系
Headless Mode 是 Claude Code CLI 的能力,而 Claude Code SDK(TypeScript/Python)提供了更底层的编程接口:
| 特性 | Headless Mode | SDK |
|---|---|---|
| 使用方式 | Shell 命令 | 代码集成 |
| 适用场景 | 脚本、CI/CD | 应用开发 |
| 上下文管理 | 手动(session_id) | 自动 |
| 工具生态 | CLI 内置 | 完全可定制 |
SDK 示例(TypeScript):
typescript
import { Claude } from "@anthropic/claude-code";
const claude = new Claude();
const result = await claude.run({
prompt: "Review this code",
tools: ["Read", "Grep"],
});总结
Headless Mode 将 Claude Code 从交互式工具转变为自动化工程团队成员:
- 核心命令:
claude -p "prompt"启用无头模式 - 输出格式:text(默认)、json(程序解析)、stream-json(实时)
- 会话管理:
--resume/--continue维持上下文 - 典型场景:CI/CD 集成、代码审查、事件响应、批量处理
- 最佳实践:JSON 输出 + 错误处理 + 超时控制 + 速率限制