Claude Code 支持程序化调用(Programmatic Usage),通过 -p 标志非交互式运行,适用于脚本自动化、CI/CD 流水线和 Shell 工作流。底层 Agent SDK 同时提供 Python 和 TypeScript 包,支持原生消息对象和回调。
基础用法:-p 标志
在任何 claude 命令中加上 -p(--print)标志,即可非交互式运行:
claude -p "What does the auth module do?"所有 CLI 选项均可与 -p 配合使用。
-p模式不可用/commit等 Slash 命令和 Built-in Commands(这些只在交互模式下可用),改为描述你想完成的任务。
结构化输出
三种输出格式
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 # 实时流式 JSONJSON 格式示例
claude -p "Summarize this project" --output-format json响应包含 result(文本结果)、session_id(会话 ID)和使用量等元数据。
按 Schema 提取结构化数据
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 解析响应
# 提取文本结果
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'流式响应
claude -p "Explain recursion" \
--output-format stream-json \
--verbose \
--include-partial-messages每行输出一个 JSON 事件对象,使用 jq 过滤出文本流:
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 无需询问即可使用特定工具:
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"自动创建 Commit
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。
自定义系统提示词
# 在保留 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."续接对话
# 第一轮
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 续接特定会话:
# 获取 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 安全审查
- 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
#!/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 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 官方文档