Appearance
编程式运行 Claude Code
Claude Code CLI 的 -p(--print)标志让你无需交互界面即可在脚本、CI/CD 和自动化任务中调用 Claude。搭配 --bare 模式可跳过本地配置加载,保证每台机器结果一致;--output-format 支持纯文本、JSON 和流式 JSON 三种格式;--allowedTools 预批准工具执行权限。对于需要结构化输出和工具回调的场景,Anthropic 还提供官方 Python 和 TypeScript Agent SDK。
Agent SDK 与 Claude Code 使用相同的工具、代理循环和上下文管理机制,提供 CLI(脚本/CI/CD)和 Python/TypeScript 包两种接入方式。
通过 CLI 编程式运行:加入 -p 和提示词,搭配任意 CLI 选项:
bash
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"本页介绍通过 CLI(claude -p)使用 Agent SDK 的方式。如需结构化输出、工具批准回调和原生消息对象等高级能力,参见 Agent SDK 完整文档。
基本用法
在任意 claude 命令中加入 -p(或 --print)标志即可非交互运行。支持所有 CLI 选项,包括:
查询代码库信息:
bash
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 服务器影响。
bash
claude --bare -p "Summarize this file" --allowedTools "Read"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> |
bare 模式跳过 OAuth 和密钥链读取,认证必须通过 ANTHROPIC_API_KEY 或 --settings 中的 apiKeyHelper 提供。Bedrock、Vertex 和 Foundry 使用各自的 provider 凭据。
输出格式
用 --output-format 控制响应格式:
text(默认):纯文本json:含结果、session ID 和元数据的结构化 JSONstream-json:换行符分隔的 JSON,支持实时流式处理
获取 JSON 输出
bash
claude -p "Summarize this project" --output-format json使用 --output-format json 配合 --json-schema 可以获取符合特定 Schema 的结构化输出,结果在响应的 structured_output 字段中:
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"]}'流式响应
用 --output-format stream-json 配合 --verbose 和 --include-partial-messages 实时接收 token。每行是一个 JSON 事件对象:
bash
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages用 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'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 | 错误类型:rate_limit、server_error 等 |
预批准工具
用 --allowedTools 让 Claude 直接使用特定工具无需提示:
bash
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"也可以设置整个会话的 permission mode:
dontAsk:拒绝所有未在permissions.allow规则中的工具,适合锁定的 CI 环境acceptEdits:允许写文件和常见文件系统命令(mkdir、touch、mv、cp)无需提示
bash
claude -p "Apply the lint fixes" --permission-mode acceptEdits常用示例
创建 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 *) 允许所有以 git diff 开头的命令。注意 * 前要有空格,否则 Bash(git diff*) 会意外匹配 git diff-index。
自定义系统提示
bash
gh pr diff "$1" | claude -p \
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
--output-format json继续对话
用 --continue 继续最近的对话,或用 --resume 加 session ID 继续指定对话:
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并行运行多个对话时,捕获 session ID 来恢复特定会话:
bash
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
常见问题
Q: claude -p 和直接运行 claude 有什么区别?
claude -p 是非交互模式,输出结果后立即退出,适合脚本调用。直接运行 claude 会进入交互式会话,可以多轮对话。两者底层使用相同的模型和工具。
Q: bare 模式和普通 -p 模式有什么区别,什么时候该用 bare?
普通 -p 模式会加载 CLAUDE.md、MCP 服务器、hooks 和插件等本地配置,跟交互式会话一样。bare 模式跳过这些,每台机器行为一致。CI/CD 流水线、需要可复现结果的脚本都应使用 bare 模式。
Q: 如何在 CI 中安全使用 Claude Code,防止权限过宽?
推荐 --bare + --allowedTools 精确限定允许的工具,或使用 --permission-mode dontAsk 只允许 permissions.allow 规则中的工具。不要在 CI 中使用 acceptEdits 等宽松模式,除非你明确知道 Claude 需要写文件权限。