以编程方式运行
用 claude -p 在脚本和 CI 中非交互运行 Claude Code:bare 模式、管道、结构化输出、流式输出、自动批准工具、继续对话。
Agent SDK 提供驱动 Claude Code 的同一套工具、智能体循环和上下文管理。它既可以作为用于脚本和 CI/CD 的 CLI,也可以作为 Python 和 TypeScript 包用于完整的编程控制。
非交互模式下,传 -p 加你的提示词和需要的 CLI 选项:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"本页讲通过 CLI(claude -p)使用 Agent SDK。想用带结构化输出、工具批准回调和原生消息对象的 Python 与 TypeScript SDK 包,见官方 Agent SDK 文档。
基本用法
给任何 claude 命令加上 -p(或 --print)标志即可非交互运行。并非所有 CLI 选项都能与 -p 组合:--bg 会被拒绝,带任务描述的 --cloud 也会被拒绝。常用的搭配:
--continue:继续对话--allowedTools:自动批准工具--output-format:结构化输出
claude -p "What does the auth module do?"成功时 Claude Code 以退出码 0 退出,运行失败时以非零码退出,所以脚本可以根据退出状态分支。
用 bare 模式更快启动
加 --bare 可以减少启动时间:跳过 Hook、Skill、自定义命令、子智能体、已安装的插件、MCP 服务器、自动记忆和 CLAUDE.md 的自动发现。适合在每台机器上都要得到同样结果的 CI 和脚本:队友 ~/.claude 里的 Hook 或项目 .mcp.json 里的 MCP 服务器都不会运行,因为 bare 模式从不读取它们。
不加
--bare时,-p会话会运行项目.claude/settings.json里的 Hook 并连接.mcp.json里的服务器,哪怕在你从未信任过的文件夹里也是如此;-p会话不显示工作区信任对话框,也没有逐服务器批准提示。
claude --bare -p "Summarize README.md" --allowedTools "Read"运行前要设置 ANTHROPIC_API_KEY,因为 bare 模式不使用你的订阅登录(它从不读取 OAuth 凭据或系统钥匙串)。在 bare 模式下 Claude 能使用 Bash、文件读取和文件编辑工具,需要的其他上下文用标志传入:
| 要加载 | 使用 |
|---|---|
| 系统提示补充 | --append-system-prompt、--append-system-prompt-file |
| 设置 | --settings <file-or-json> |
| MCP 服务器 | --mcp-config <file-or-json> |
| 自定义智能体 | --agents <json> |
| 插件 | --plugin-dir <path>、--plugin-url <url> |
--bare 是脚本和 SDK 调用的推荐模式,在未来的版本里会成为 -p 的默认模式。
示例
在 CI 或其他脚本环境里,加上 --bare 让 Claude Code 不加载宿主机的 Hook、插件等。
用管道传入数据
非交互模式会读取 stdin,所以可以像其他命令行工具一样把数据用管道传入、把响应重定向出去:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt用 --output-format json 时,响应负载包含 total_cost_usd 和按模型的成本明细,脚本调用方无需查看用量仪表盘就能追踪花费。通过管道传入的 stdin 上限为 10MB,超出会报错并以非零状态退出;处理更大的输入,把内容写到文件里并在提示中引用文件路径。
把 Claude 加进构建脚本
把非交互调用包进脚本,让 Claude 充当项目专用的 linter 或评审员。这个 package.json 脚本把相对 main 的 diff 通过管道传给 Claude,让它报告拼写错误(用管道传 diff 意味着 Claude 不需要 Bash 权限去读它):
{
"scripts": {
"lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}运行:npm run lint:claude。
获取结构化输出
用 --output-format 控制响应的返回方式:
text(默认):纯文本输出json:带结果、会话 ID 和元数据的结构化 JSONstream-json:用换行分隔的 JSON,用于实时流式输出
claude -p "Summarize this project" --output-format json想让输出符合特定模式,把 --output-format json 和 --json-schema(一份 JSON Schema 定义)一起用。响应包含关于请求的元数据(会话 ID、用量等),结构化输出在 structured_output 字段里:
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"]}'可以用 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'流式响应
用 --output-format stream-json 加 --verbose 和 --include-partial-messages 接收生成中的 token,每一行是一个代表事件的 JSON 对象,流的最后一行是带最终响应文本、成本和会话元数据的 result 消息:
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages用 jq 过滤文本增量,只显示流式文本(-r 输出原始字符串,-j 不加换行连接,让 token 连续流出):
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'子智能体的消息会出现在流里,作为 parent_tool_use_id 字段为派生它的工具调用 ID 的 assistant 和 user 消息;主对话的消息在该字段里是 null。
自动批准工具
用 --allowedTools 让 Claude 不经提示就使用某些工具。列出 Read 和 Edit 让 Claude 无需请求权限就能读取和编辑文件;列出 Bash 对 shell 命令也一样(以 auto 模式启动的运行除外):
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"想为整个会话设置基线而不是逐个列工具,传一个权限模式:
auto:--permission-mode auto,让分类器审查大多数动作dontAsk:Claude Code 拒绝每个本来会弹提示的调用,适合锁定的 CI 运行acceptEdits:Claude 无需提示就写文件,并自动批准mkdir、touch、mv、cp等常见文件系统命令
claude -p "Apply the lint fixes" --permission-mode acceptEdits在无人值守的运行里关闭权限提示:当没有人可回答权限提示时(例如定时任务),传 --permission-prompts none(需要 v2.1.259 或更新版本)。本来会弹提示的任何东西都会被拒绝(除非 PermissionRequest Hook 允许),Claude 被告知没有人能批准这个请求、不要重试,运行继续:
claude -p "Update the dependency pins and run the tests" --permission-mode auto --permission-prompts none创建提交
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 *) 允许任何以 git diff 开头的命令。* 前的空格很重要:没有它,Bash(git diff*) 还会匹配 git diff-index。
在 -p 模式下命令支持有差异:用户调用的 Skill 和自定义命令可用(在提示字符串里写 /skill-name,Claude Code 在运行前展开);只在终端界面里运行的内置命令(如 /login)不可用;/model、/effort、/fast 等接受值作为参数(如 /model sonnet);改设置时给 /config 传 key=value,如 /config thinking=false。
自定义系统提示
用 --append-system-prompt 在保留 Claude Code 默认行为的同时添加指令。下面的例子把 PR diff 通过管道传给 Claude,让它审查安全漏洞:
gh pr diff "$1" | claude -p \
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
--output-format json更多选项见系统提示标志,包括用 --system-prompt 完全替换默认提示。
继续对话
用 --continue 继续最近一次对话,或用带会话 ID 的 --resume 继续某个特定对话:
# 第一次请求
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如果同时运行多个对话,捕获会话 ID 以便恢复特定的那个:
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"两条命令可以在不同的目录运行:Claude Code 会在这台机器的任何项目里按 ID 找到会话。也可以给 --resume 传会话 .jsonl 转录文件的绝对路径。
下一步
- Agent SDK 快速上手:用 Python 或 TypeScript 构建你的第一个智能体
- CLI 参考:所有 CLI 标志和选项
- GitHub Actions:在 GitHub 工作流里使用 Agent SDK