Claude Code 编程式调用:-p、bare 模式与结构化输出
CLI 的 -p(--print)标志让你在脚本和 CI/CD 中直接运行 Claude Code,无需进入交互式界面。加上 --bare 可跳过 CLAUDE.md、MCP 服务器、hooks 等本地配置,保证每台机器结果一致。支持纯文本、JSON 和流式 JSON 输出;通过 --allowedTools 预批准工具;--continue 可延续对话。对于结构化输出、工具回调等高级场景,建议使用 Python/TypeScript Agent SDK。注意:2026 年 6 月 15 日起,claude -p 的用量将独立于交互式额度,核销新增的月度 Agent SDK 信用。详见 Claude Agent SDK 计划说明。
Agent SDK 与 Claude Code 共用同一套工具、代理循环和上下文管理机制,提供 CLI(适合脚本/CI/CD)和 Python/TypeScript 包两种接入方式。
通过 CLI 编程式运行的基本命令:加入 -p 和提示词,搭配任意 CLI 选项:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
本页文档侧重 CLI(claude -p)方式。如需结构化输出、工具批准回调和原生消息对象等能力,参见 Agent SDK 完整文档。
基本用法
在任意 claude 命令中加入 -p(或 --print)标志即可非交互运行。所有 CLI 选项都支持配合 -p,包括:
--continue:延续之前的对话--allowedTools:自动批准工具--output-format:控制输出格式
示例:询问代码库中的模块功能:
claude -p "What does the auth module do?"
bare 模式:更快启动,结果一致
添加 --bare 可以跳过 hooks、skills、插件、MCP 服务器、自动记忆和 CLAUDE.md 的自动发现,大幅减少启动时间。不加 --bare 时,claude -p 会加载与交互式会话相同的上下文,包括工作目录和 ~/.claude 中的所有配置。
bare 模式适合 CI 和脚本:每台机器的结果都一样,不会受队友 ~/.claude 中的 hook 或项目 .mcp.json 中的 MCP 服务器影响。只有你通过 flag 显式传入的配置才生效。
claude --bare -p "Summarize this file" --allowedTools "Read"
bare 模式下 Claude 可以使用 Bash、文件读取和文件编辑工具。如需加载额外上下文,通过以下 flag 显式传入:
| 需要加载的内容 | 使用方式 |
|---|---|
| 系统提示补充 | --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 模式跳过 OAuth 和密钥链读取。Anthropic 认证必须通过 ANTHROPIC_API_KEY 环境变量或 --settings JSON 中的 apiKeyHelper 提供。Bedrock、Vertex 和 Foundry 使用各自的 provider 凭据。
--bare是脚本和 SDK 调用的推荐模式,未来版本中将成为-p的默认行为。
常用示例
这些示例突出 CLI 的常见模式。对于 CI 和其他脚本化调用,建议添加 --bare 以避免加载本地配置。
管道传数据
非交互模式读取标准输入,因此可以像普通命令行工具一样管道传数据、重定向输出。
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
配合 --output-format json,响应会包含 total_cost_usd 和按模型分解的成本,方便脚本跟踪每次调用的花费,无需再去用量控制台查看。
自 Claude Code v2.1.128 起,管道输入的上限为 10MB。超过上限时,Claude Code 会输出明确的错误信息并以非零状态码退出。对于更大的输入,建议将内容写入文件,在提示中引用文件路径。
集成到构建脚本
你可以把非交互调用封装到脚本中,让 Claude 担任项目专属的 linter 或 reviewer。
以下 package.json 脚本把与 main 分支的 diff 管道传给 Claude,让它报告拼写错误。管道传 diff 意味着 Claude 不需要 Bash 权限去读取文件;转义的双引号保证脚本可在 Windows 上移植:
{
"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.\""
}
}
获取结构化输出
使用 --output-format 控制响应格式:
text(默认):纯文本json:含结果、session ID 和元数据的 JSONstream-json:换行符分隔的 JSON,支持实时流式处理
claude -p "Summarize this project" --output-format json
如需输出符合特定 schema,使用 --output-format json 配合 --json-schema 传入 JSON Schema 定义。结果在响应的 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,每行是一个 JSON 事件对象:
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages
以下示例用 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'
当 API 请求因可重试错误失败时,Claude Code 在重试前会先发出 system/api_retry 事件。你可以利用此事件显示重试进度或实现自定义退避逻辑。
| 字段 | 类型 | 说明 |
|---|---|---|
type |
"system" |
消息类型 |
subtype |
"api_retry" |
重试事件标识 |
attempt |
integer | 当前尝试次数,从 1 开始 |
max_retries |
integer | 允许的最大重试次数 |
retry_delay_ms |
integer | 下次尝试前的等待毫秒数 |
error_status |
integer 或 null | HTTP 状态码,连接错误时为 null |
error |
string | 错误类别:authentication_failed、rate_limit、server_error 等 |
uuid |
string | 唯一事件标识 |
session_id |
string | 事件所属 session |
system/init 事件报告 session 元数据,包括模型、工具、MCP 服务器和已加载的插件。除非设置了 CLAUDE_CODE_SYNC_PLUGIN_INSTALL 环境变量(此时 plugin_install 事件会先出现),否则它是流中的第一个事件。通过插件字段可以判断 CI 中是否有插件加载失败:
| 字段 | 类型 | 说明 |
|---|---|---|
plugins |
array | 成功加载的插件,每个包含 name 和 path |
plugin_errors |
array | 插件加载错误(依赖版本不满足、--plugin-dir 路径缺失或归档无效等)。受影响的插件被降级,不会出现在 plugins 中。无错误时省略此键 |
当设置了 CLAUDE_CODE_SYNC_PLUGIN_INSTALL 时,Claude Code 会在第一次对话前发出 system/plugin_install 事件报告市场插件的安装进度。你可以用这些事件在 UI 中显示安装进度。
| 字段 | 类型 | 说明 |
|---|---|---|
type |
"system" |
消息类型 |
subtype |
"plugin_install" |
插件安装事件标识 |
status |
"started"、"installed"、"failed" 或 "completed" |
started 和 completed 包裹整个安装过程;installed 和 failed 报告单个市场 |
name |
string, 可选 | 市场名称,在 installed 和 failed 中出现 |
error |
string, 可选 | 失败消息,在 failed 中出现 |
uuid |
string | 唯一事件标识 |
session_id |
string | 事件所属 session |
如需通过回调实现更高级的流式处理,参见 Agent SDK 实时流式响应 文档。
自动批准工具
使用 --allowedTools 让 Claude 直接使用某些工具,无需确认提示。示例:运行测试套件并修复失败,允许 Bash、读文件和编辑文件:
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
也可以设置一个整场会话的权限模式。dontAsk 拒绝所有不在 permissions.allow 规则或只读命令集中的工具,适合锁定的 CI 环境。acceptEdits 允许写文件并自动批准 mkdir、touch、mv、cp 等命令。其他 shell 命令和网络请求仍需在 --allowedTools 中列出或配置 permissions.allow 规则,否则会被拒绝导致运行中止:
claude -p "Apply the lint fixes" --permission-mode acceptEdits
创建提交
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。
自定义系统提示
使用 --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 继续最近的对话,或使用 --resume 加 session ID 恢复特定对话。示例:先进行一次审查,随后提后续问题:
# 第一次请求
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
如果同时运行多个对话,捕获 session ID 以恢复指定对话:
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
后续步骤
- Agent SDK 快速开始:用 Python 或 TypeScript 构建第一个 agent
- CLI 参考:所有 CLI 标志和选项
- GitHub Actions:在 GitHub 工作流中使用 Agent SDK
- GitLab CI/CD:在 GitLab 流水线中使用 Agent SDK
常见问题
claude -p 和直接运行 claude 有什么区别?
claude -p 是非交互模式,输出结果后立即退出,适合脚本和 CI/CD 调用。直接运行 claude 进入交互式会话,可以多轮对话。两者底层使用相同的模型和工具,但交互模式下用户可传入 / 命令、调用技能,而 -p 只能通过 flag 控制。
bare 模式什么时候用?
CI/CD 流水线、需要可复现结果的脚本应强制使用 --bare。普通开发环境在尝试一次性代码分析时也可以使用 bare 模式加速。如果不需要 hooks、MCP 服务器、CLAUSE.md 等本地配置,就加 --bare;如果需要这些配置辅助 Claude 理解项目,则不加。
–allowedTools 和 --permission-mode 有什么区别?
--allowedTools 清单式指定允许的具体工具,更细粒度。--permission-mode 设置整个会话的权限策略:dontAsk 拒绝默认之外的所有工具,acceptEdits 自动批准文件写入和常见文件系统命令。两者可以结合使用,--allowedTools 的规则优先于 --permission-mode 的默认行为。