关于 claude-headless-mode
claude-headless-mode 是一项技能,介绍如何在脚本、CI 和自动化中通过 `claude -p` 非交互运行 Claude。内容涵盖文本、JSON 和流式输出、按模式约束结果、权限设置及跨调用任务协调。
主要功能
- 01通过 `claude -p` 非交互执行
- 02文本、JSON 与流式输出
- 03按 JSON Schema 约束响应
- 04权限与工具控制
- 05共享任务协调
适用场景
- 01在 CI 中解析结构化结果
- 02批量审查多个文件
- 03协调多次调用中的脚本任务
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ majesticlabs-dev/ majestic-marketplace --skill claude-headless-mode安装后在 Claude Code 中输入/claude-headless-mode确认已加载。
详细介绍
Claude 无头模式
在脚本、CI 和自动化中使用 claude -p(或 --print)进行非交互式执行。
基本用法
# Simple prompt
claude -p "Summarize this repo"
# With file input
claude -p "Review this code" < file.py
# Pipe output
claude -p "List all functions" | grep "def "
输出格式
| 格式 | 标志 | 使用场景 |
|---|---|---|
| 文本 | --output-format text | 人类可读(默认) |
| JSON | --output-format json | 单个 JSON 结果 |
| 流式 JSON | --output-format stream-json --verbose | 实时流式输出 |
文本输出(默认)
claude -p "What is 2+2?"
# Output: 4
JSON 输出
claude -p "What is 2+2?" --output-format json
返回包含元数据的封装对象:
{
"type": "result",
"subtype": "success",
"result": "4",
"duration_ms": 1234,
"total_cost_usd": 0.01,
"session_id": "...",
"structured_output": null
}
仅提取结果:
claude -p "What is 2+2?" --output-format json | jq -r '.result'
流式 JSON 输出
claude -p "Long analysis" --output-format stream-json --verbose
- 随着执行进展,以换行符分隔的 JSON 流会持续输出
- 实时显示工具调用、消息和进度
- 最后一行包含结果
- 需要
--verbose标志
提取最终结果:
claude -p "Analyze code" --output-format stream-json --verbose \
| tee /dev/stderr \
| tail -1 \
| jq -r '.result'
使用 JSON Schema 进行结构化输出
强制 Claude 返回符合特定架构的数据:
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"functions": { "type": "array", "items": { "type": "string" } }
},
"required": ["functions"]
}'
结果会出现在 structured_output 字段中:
{
"result": "...",
"structured_output": {
"functions": ["login", "logout", "verify_token"]
}
}
架构示例
简单对象:
{
"type": "object",
"properties": {
"answer": { "type": "integer" }
},
"required": ["answer"]
}
任务结果(成功/失败):
{
"type": "object",
"properties": {
"status": { "type": "string", "enum": ["success", "failure"] },
"summary": { "type": "string" },
"files_changed": { "type": "array", "items": { "type": "string" } },
"error_category": { "type": "string" },
"suggestion": { "type": "string" }
},
"required": ["status", "summary"]
}
从架构结果中提取:
OUTPUT=$(claude -p "$PROMPT" --output-format json --json-schema "$SCHEMA")
STATUS=$(echo "$OUTPUT" | jq -r '.structured_output.status')
SUMMARY=$(echo "$OUTPUT" | jq -r '.structured_output.summary')
常用选项
| 选项 | 说明 |
|---|---|
-p, --print | 无头模式(必需) |
--output-format | text、json、stream-json |
--json-schema | 强制使用输出架构 |
--verbose | stream-json 所需 |
--model | 选择模型(sonnet、opus、haiku) |
--max-turns | 限制 Agent 交互轮数 |
--permission-mode | bypassPermissions、plan 等 |
--allowedTools | 限制可用工具 |
权限模式
# Skip all permission prompts (trusted environments only)
claude -p "Fix all linting errors" --permission-mode bypassPermissions
# Plan mode (read-only exploration)
claude -p "Analyze architecture" --permission-mode plan
示例
CI/CD 集成
# Run tests and get structured result
RESULT=$(claude -p "Run tests and report results" \
--output-format json \
--json-schema '{"type":"object","properties":{"passed":{"type":"boolean"},"failures":{"type":"array","items":{"type":"string"}}},"required":["passed"]}')
if [ "$(echo $RESULT | jq '.structured_output.passed')" = "true" ]; then
echo "Tests passed"
else
echo "Tests failed"
exit 1
fi
批处理
for file in src/*.py; do
claude -p "Review $file for security issues" \
--output-format json \
--json-schema '{"type":"object","properties":{"issues":{"type":"array"}},"required":["issues"]}' \
| jq ".structured_output.issues"
done
在全新上下文中执行任务
# Each invocation is independent (no conversation history)
claude -p "Task 1: Create migration" --output-format json
claude -p "Task 2: Add model" --output-format json
claude -p "Task 3: Write tests" --output-format json
任务协调
使用 CLAUDE_CODE_TASK_LIST_ID 在多次无头模式调用之间共享 TaskList。
环境变量
# All invocations share the same TaskList
export CLAUDE_CODE_TASK_LIST_ID="my-project"
claude -p "Use TaskCreate to add: Setup database"
claude -p "Use TaskCreate to add: Write migrations"
claude -p "Use TaskList to show all tasks" # Shows both tasks
模式:协调器 + 工作器
TASK_LIST_ID="epic-$(date +%Y%m%d)"
export CLAUDE_CODE_TASK_LIST_ID="$TASK_LIST_ID"
# Orchestrator creates tasks
claude -p "Use TaskCreate for each: Task 1, Task 2, Task 3"
# Workers execute (each sees shared TaskList)
for task_id in 1 2 3; do
claude -p "Use TaskUpdate to mark task #$task_id as in_progress, implement it, then mark completed"
done
# Check final state
claude -p "Use TaskList to show status"
任务工具
| 工具 | 用途 |
|---|---|
TaskCreate | 创建带有主题和描述的新任务 |
TaskList | 列出所有任务及其状态 |
TaskUpdate | 更新任务状态(in_progress、completed)或添加 blockedBy |
TaskGet | 获取特定任务的完整详情 |
依赖关系
# Task 2 depends on Task 1
claude -p "Use TaskUpdate on task #2 to set blockedBy: [1]"
任务会持久保存在 ~/.claude/tasks/ 中,并在会话重启后继续保留。
注意事项
- 每次调用
-p都会启动一个全新实例(不沿用之前运行的上下文) - 使用
--output-format json进行程序化解析 structured_output字段包含经过架构验证的数据result字段包含原始文本响应- 流式 JSON 需要
--verbose标志 - JSON 输出中提供费用信息:
total_cost_usd
评论
支持 Markdown