教程

Claude Code 程序化调用完全指南:-p 标志、结构化输出、流式响应与会话续接

Claude Code 程序化调用完全指南:-p/--print 非交互模式基础用法、三种输出格式(text/json/stream-json)、按 JSON Schema 提取结构化数据(structured_output 字段)、jq 解析响应、流式响应(stream-json + --verbose + --include-partial-messages + jq -rj 过滤 text_delta)、--allowedTools 自动批准工具(权限规则语法/末尾空格注意事项)、自动创建 Commit 示例、--append-system-prompt/--system-prompt 系统提示词、--continue/--resume 会话续接(Session ID 捕获)、GitHub Actions CI/CD 集成,以及 Python/TypeScript Agent SDK 高级用法入口。

2026/3/84分钟 阅读ClaudeEagle

Claude Code 支持程序化调用(Programmatic Usage),通过 -p 标志非交互式运行,适用于脚本自动化、CI/CD 流水线和 Shell 工作流。底层 Agent SDK 同时提供 Python 和 TypeScript 包,支持原生消息对象和回调。

基础用法:-p 标志

在任何 claude 命令中加上 -p--print)标志,即可非交互式运行:

bash
claude -p "What does the auth module do?"

所有 CLI 选项均可与 -p 配合使用。

-p 模式不可用 /commit 等 Slash 命令和 Built-in Commands(这些只在交互模式下可用),改为描述你想完成的任务。

结构化输出

三种输出格式

bash
claude -p "Summarize this project" --output-format text        # 纯文本(默认)
claude -p "Summarize this project" --output-format json        # 含元数据的 JSON
claude -p "Summarize this project" --output-format stream-json # 实时流式 JSON

JSON 格式示例

bash
claude -p "Summarize this project" --output-format json

响应包含 result(文本结果)、session_id(会话 ID)和使用量等元数据。

按 Schema 提取结构化数据

bash
claude -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

响应中 structured_output 字段包含符合 Schema 的数据。

用 jq 解析响应

bash
# 提取文本结果
claude -p "Summarize this project" --output-format json | jq -r '.result'

# 提取结构化输出
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'

流式响应

bash
claude -p "Explain recursion" \
  --output-format stream-json \
  --verbose \
  --include-partial-messages

每行输出一个 JSON 事件对象,使用 jq 过滤出文本流:

bash
claude -p "Write a poem" \
  --output-format stream-json \
  --verbose \
  --include-partial-messages | \
  jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

-r(raw 字符串,无引号)和 -j(不加换行符)使 Token 连续流出。

自动批准工具

使用 --allowedTools 让 Claude 无需询问即可使用特定工具:

bash
claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"

自动创建 Commit

bash
claude -p "Look at my staged changes and create an appropriate commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

--allowedTools 使用权限规则语法Bash(git diff *) 中末尾 * 前的空格很重要——Bash(git diff *) 只匹配 git diff 开头,而 Bash(git diff*) 还会匹配 git diff-index

自定义系统提示词

bash
# 在保留 Claude Code 默认行为的同时追加指令
gh pr diff "$1" | claude -p \
  --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
  --output-format json

# 完全替换默认系统提示词
claude -p "Review this code" \
  --system-prompt "You are a Python expert. Focus on performance."

续接对话

bash
# 第一轮
claude -p "Review this codebase for performance issues"

# 续接最近的对话
claude -p "Now focus on the database queries" --continue
claude -p "Generate a summary of all issues found" --continue

使用 --resume + Session ID 续接特定会话:

bash
# 获取 Session ID
SESSION=$(claude -p "Review this codebase" --output-format json | jq -r '.session_id')

# 续接指定会话
claude -p "Now check the auth module" --resume "$SESSION"

典型 CI/CD 集成示例

GitHub Actions PR 安全审查

yaml
- name: Security Review
  run: |
    gh pr diff ${{ github.event.number }} | \
    claude -p \
      --append-system-prompt "Review for security vulnerabilities. Output JSON with 'issues' array." \
      --output-format json \
      --allowedTools "Read" > review.json
    cat review.json | jq '.result'

Shell 脚本自动修复 Bug

bash
#!/bin/bash
claude -p "Find and fix the bug in auth.py" \
  --allowedTools "Read,Edit,Bash" \
  --output-format json | jq -r '.result'

Python / TypeScript SDK

对于更复杂的场景(工具批准回调、原生消息对象、高级流处理),使用 Agent SDK 包:

python
# Python SDK
from anthropic_agent_sdk import ClaudeCode

cc = ClaudeCode()
result = cc.run("Find and fix the bug in auth.py",
               allowed_tools=["Read", "Edit", "Bash"])
print(result.text)

完整 Python/TypeScript SDK 文档参见 platform.claude.com/docs/en/agent-sdk


原文:Run Claude Code programmatically - Claude Code Docs | 来源:Anthropic 官方文档

相关文章推荐

教程Claude Code Agent SDK 完整开发指南:构建自定义 AI Agent 工作流Claude Code Agent SDK 完整开发指南:TypeScript/Python 两种 SDK 用法;四种权限模式(只读/Auto/完全权限/自定义白名单);流式响应实时接收输出;自定义工具注入(queryDatabase/sendSlackNotification 示例);多 Agent 编排(主 Agent + 并行子 Agent);GitHub Actions CI/CD 集成;错误处理和指数退避重试;成本监控(按模型计价)。2026/5/3教程Claude Code 无头模式与 Agent SDK:非交互式脚本、CI/CD 集成完全指南Claude Code 无头模式与 Agent SDK 完全指南:-p 参数基础用法、三种输出格式(text/json/stream-json)、JSON Schema 结构化输出、精细工具权限控制、多轮对话 Session 管理,以及 GitHub Actions PR 安全审查和批量处理的 CI/CD 实战场景。2026/3/2教程Claude Code 自定义 Agents 完整指南:创建专用 AI 编程助手Claude Code 自定义 Agents 完整指南:Agent 定义文件格式(Frontmatter 字段:name/description/tools/permissionMode/model/effort/context);4 种调用方式(/agents 界面/--agent CLI/对话提及/Print 模式自动化);4 个实战 Agent 配置(安全审查员/数据库优化顾问/无障碍合规检查/TypeScript 类型安全/CI 失败分析师);skillOverrides 控制可见性;context: fork 独立上下文;以及在 GitHub Actions 里使用 Agent 的 CI 配置示例。2026/5/7教程Claude Code 与 GitHub Actions 集成完全指南:CI/CD 自动化的 5 个实用模式Claude Code 整合 GitHub Actions 的 5 个完整可用模式:PR 自动代码审查(触发+评论)、空 PR 自动生成描述、测试覆盖率分析和建议、安全扫描(发现 Critical 问题阻断合并)、变更日志自动生成。每个模式含完整 YAML 配置,以及 API Key 安全管理和成本控制建议。2026/4/24教程Claude Code GitHub Actions 实战:用 @claude 让 AI 自动修 bug、实现功能、生成 PRClaude Code GitHub Actions 实战教程:配置 @claude 命令触发 AI 自动修 bug、实现功能、生成 PR。含 2 步快速配置、3 个工作流示例、安全设置和常见问题排查。2026/4/9教程Claude Code + GitHub Actions:自动化代码审查与 CI/CD 集成完全指南Claude Code GitHub Actions 完整配置指南:5 分钟快速安装(GitHub App + API Key Secret + Workflow 文件)、四大使用场景(按需 PR 审查/Issue 自动实现/快速修复/自动 Changelog)、每 PR 自动触发审查配置、高级参数(模型/轮数/工具限制/AWS Bedrock)与安全最佳实践。2026/3/13