SuperAPI AI 工具集

claude-code-headless

编程与开发

查看项目

更新于 10-13 16:36

技能介绍

用途

Claude Code Headless 说明如何在不使用交互式 UI 的情况下,从脚本中程序化运行 Claude Code。它适用于需要把 Claude Code 嵌入自动化流程的场景,例如脚本、CI/CD 流水线与多轮自动化任务。

主要能力

非交互执行

使用 -p 或 --print 进入非交互(headless)模式:

claude -p "Explain this code" --allowedTools "Read,Grep"

输出格式

--output-format 支持 text、json、stream-json 三种格式。

文本(默认)直接输出人类可读的响应:

claude -p "Hello"

JSON 输出便于解析:

claude -p "Hello" --output-format json

其结构示例为:

{
  "type": "result",
  "subtype": "success",
  "result": "Hello! How can I help?",
  "session_id": "abc123",
  "total_cost_usd": 0.001,
  "duration_ms": 1234,
  "num_turns": 1
}

stream-json 则为每条消息提供实时 JSONL 输出:

claude -p "Hello" --output-format stream-json

会话恢复与延续

可先以 JSON 输出运行,再用 jq 提取 session_id 进行后续操作:

claude -p "Start analysis" --output-format json > result.json
session=$(jq -r '.session_id' result.json)
claude --resume "$session" "Now fix the issues"

相关选项包括 -r / --resume(按会话 ID 恢复)和 -c / --continue(继续最近会话)。

工具与权限控制

用 --allowedTools 与 --disallowedTools 以逗号分隔的方式指定允许或禁止的工具:

claude -p "Analyze the codebase" \
  --allowedTools "Read,Grep,Glob" \
  --disallowedTools "Write,Edit,Bash"

权限模式如下:

  • Default(无标志):提示请求权限。
  • --permission-mode acceptEdits:自动接受文件更改。
  • --permission-mode bypassPermissions:跳过所有提示。

其他 CLI 选项

  • --mcp-config:MCP 服务器配置 JSON 的路径。
  • --verbose:启用详细日志。
  • --append-system-prompt:向系统提示追加内容。

使用方式

CI/CD 集成示例

claude -p "Review this PR diff" \
  --permission-mode acceptEdits \
  --output-format json \
  --append-system-prompt "Focus on security issues"

多轮自动化示例

session=$(claude -p "Start task" --output-format json | jq -r '.session_id')
claude --resume "$session" "Continue with step 2"
claude --resume "$session" "Finalize and report"

错误处理示例

result=$(claude -p "Task" --output-format json)
if [[ $(echo "$result" | jq -r '.is_error') == "true" ]]; then
    echo "Error: $(echo "$result" | jq -r '.result')" >&2
    exit 1
fi

适用场景

根据资料,常见模式包括带工具限制的脚本、CI/CD 集成以及多轮自动化。

限制

资料未提供具体的环境要求、安装方式、收费与价格信息、性能或效果说明,也未提供可用平台限制,这些内容暂未提供。资料中列出的附加资源包括 ./references/cli-options.md(完整 CLI 标志参考)、./references/output-formats.md(输出格式 schema)、./references/integration-patterns.md(CI/CD 与脚本示例)。官方文档地址为 https://code.claude.com/docs/en/headless 和 https://code.claude.com/docs/en/settings。相关主题还包括 claude-code-hooks(自动化事件)与 claude-code-debug(故障排查)。