是什么

通过 -p(--print)标志以非交互式模式运行 Claude Code,适合脚本、CI/CD 和程序化集成。Agent SDK 提供 CLI、Python 和 TypeScript 三种接口,底层使用相同的工具、Agent 循环和上下文管理。

核心机制

基本用法:

claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"

Bare 模式(推荐用于 CI):--bare 跳过 Hooks、Skills、Plugins、MCP Servers、CLAUDE.md 的自动发现,只加载显式传入的配置,保证跨机器一致性:

claude --bare -p "Summarize this file" --allowedTools "Read"

Bare 模式下加载配置:

  • 系统提示:--append-system-prompt 或 --append-system-prompt-file
  • 设置:--settings <file-or-json>
  • MCP Servers:--mcp-config <file-or-json>
  • Agents:--agents <json>
  • Plugin:--plugin-dir <path> 或 --plugin-url <url>

管道支持:非交互式模式读取 stdin,可以管道传入数据:

cat build-error.txt | claude -p 'explain the root cause' > output.txt

结构化输出:--output-format json 返回包含 total_cost_usd 和模型成本明细的 JSON。

继续对话:--continue 继续上一个会话,--resume <session-id> 恢复指定会话。

关键细节

  • stdin 上限:10MB(超出报错,改用文件路径)
  • Bare 模式认证:必须用 ANTHROPIC_API_KEY 或 --settings 中的 apiKeyHelper,不支持 OAuth
  • 订阅计划用户:2026-06-15 起 Agent SDK 用量从独立月度额度扣除
  • Python/TypeScript SDK:支持结构化输出、工具审批回调、原生消息对象

关联

  • goal — /goal 命令支持非交互式运行
  • routines — 云端自动化(不依赖本地 CLI)
  • github-actions — CI/CD 集成

实践要点

  • CI 环境强烈推荐 --bare,避免本地配置影响结果
  • --allowedTools 预批准工具,避免权限提示阻塞脚本
  • 管道输入超过 10MB 时,将内容写入文件并在 prompt 中引用路径
  • --output-format json 便于脚本解析响应和追踪成本
  • 非交互式模式下 /goal 运行到条件满足后退出,适合 CI 质量门控