教程

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:非交互式脚本、CI/CD 集成完全指南Claude Code 无头模式与 Agent SDK 完全指南:-p 参数基础用法、三种输出格式(text/json/stream-json)、JSON Schema 结构化输出、精细工具权限控制、多轮对话 Session 管理,以及 GitHub Actions PR 安全审查和批量处理的 CI/CD 实战场景。2026/3/2教程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教程Claude Code GitHub Actions 集成指南:让 AI 自动化你的 CI/CD 流水线Claude Code GitHub Actions 让 AI 融入 GitHub 工作流,支持通过 @claude 提及触发代码审查、自动创建 PR 和修复 Bug。本文涵盖快速安装、手动配置、Beta 到 v1.0 升级指南、实用工作流示例(PR 审查、Issue 自动修复)以及 AWS Bedrock/Google Vertex AI 集成方案。2026/2/27教程Claude Code 权限管理完全指南:精确控制 AI 能执行哪些操作Claude Code 权限系统完整解析:四种权限模式(default/acceptEdits/bypassPermissions/plan)、--allowedTools 和 --disallowedTools 精确工具控制、Bash 命令白名单语法(通配符匹配)、settings.json 持久化权限配置、CLAUDE.md 中的权限规则声明、CI/CD 自动化场景的权限配置、以及如何在效率和安全之间找到平衡点。2026/3/18教程Claude Code Hooks 实战指南:5 大自动化场景、三种 Hook 类型与故障排查Claude Code Hooks 实战指南:/hooks 交互菜单四步创建桌面通知 Hook、5 大常用自动化场景(等待通知/编辑后 Prettier 格式化/退出码 2 阻止受保护文件/PostCompact 重注入上下文/ConfigChange 审计日志)、四种 Hook 类型(command/prompt-based/agent-based/HTTP Webhook)、输入/输出机制(stdin JSON/stdout 注入上下文/退出码 0 继续/2 阻止/非零警告)、结构化 JSON 输出、Matcher 过滤器语法(Edit|Write/Bash(git *)/*/空字符串)、四级存储位置,以及五大故障排查方法和调试技巧。2026/3/8教程Claude Code 定时任务(Scheduled Tasks)完全指南:/loop 命令、Cron 表达式与三日自动过期Claude Code 定时任务完整指南:/loop Bundled Skill(三种间隔写法:前置 token/trailing every/默认 10 分钟;对 Skill 命令循环执行)、一次性自然语言提醒(自动删除)、CronCreate/CronList/CronDelete 三个底层工具、运行机制(低优先级/两轮之间触发/本地时区)、随机延迟机制(重复任务 0~10% 偏移/单次任务 90 秒)、三日自动过期、Cron 表达式参考表、CLAUDE_CODE_DISABLE_CRON 禁用,以及会话级局限性(退出消失/无补偿/无持久化)和持久化替代方案(Desktop/GitHub Actions)。2026/3/8