{/* TRANSLATED — 已翻译为中文 */}

> ## 文档索引
> 在以下地址获取完整文档索引：https://code.claude.com/docs/llms.txt
> 使用此文件发现所有可用页面，然后再进一步探索。

# 以编程方式运行 Claude Code

> 使用 Agent SDK 从 CLI、Python 或 TypeScript 以编程方式运行 Claude Code。

<Note>
  从 2026 年 6 月 15 日开始，订阅计划上的 Agent SDK 和 `claude -p` 使用将从新的每月 Agent SDK 额度中扣除，与您的交互使用限制分开。有关详情，请参阅[在 Claude 计划中使用 Claude Agent SDK](https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan)。
</Note>

[Agent SDK](/cn/agent-sdk/overview) 提供与 Claude Code 相同的工具、代理循环和上下文管理。它可作为 CLI 用于脚本和 CI/CD，也可作为 [Python](/cn/agent-sdk/python) 和 [TypeScript](/cn/agent-sdk/typescript) 包提供完全的编程控制。

要以非交互模式运行 Claude Code，使用 `-p` 传递您的提示和任何 [CLI 选项](/cn/cli-reference)：

```bash theme={null}
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
```

本页介绍通过 CLI（`claude -p`）使用 Agent SDK。有关带有结构化输出、工具审批回调和原生消息对象的 Python 和 TypeScript SDK 包，请参阅 [Agent SDK 完整文档](/cn/agent-sdk/overview)。

## 基本用法

在任何 `claude` 命令中添加 `-p`（或 `--print`）标志以非交互方式运行。所有 [CLI 选项](/cn/cli-reference)都可与 `-p` 一起使用，包括：

* `--continue` 用于[继续对话](#继续对话)
* `--allowedTools` 用于[自动批准工具](#自动批准工具)
* `--output-format` 用于[结构化输出](#获取结构化输出)

此示例向 Claude 询问关于代码库的问题并打印响应：

```bash theme={null}
claude -p "What does the auth module do?"
```

### 使用裸模式更快启动

添加 `--bare` 通过跳过钩子、技能、插件、MCP 服务器、自动记忆和 CLAUDE.md 的自动发现来减少启动时间。不使用它时，`claude -p` 会加载交互式会话相同的[上下文](/cn/how-claude-code-works#上下文窗口)，包括在工作目录或 `~/.claude` 中配置的任何内容。

裸模式适用于 CI 和脚本，在每台机器上需要相同结果。队友 `~/.claude` 中的钩子或项目 `.mcp.json` 中的 MCP 服务器不会运行，因为裸模式从不读取它们。只有您明确传递的标志才会生效。

此示例在裸模式下运行一次性总结任务并预批准 Read 工具，以便调用在没有权限提示的情况下完成：

```bash theme={null}
claude --bare -p "Summarize this file" --allowedTools "Read"
```

在裸模式下，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>`             |

裸模式跳过 OAuth 和钥匙串读取。Anthropic 认证必须来自 `ANTHROPIC_API_KEY` 或传递给 `--settings` 的 JSON 中的 `apiKeyHelper`。Bedrock、Vertex 和 Foundry 使用其通常的提供商凭证。

<Note>
  `--bare` 是脚本化和 SDK 调用的推荐模式，将在未来版本中成为 `-p` 的默认模式。
</Note>

## 示例

这些示例突出常见的 CLI 模式。对于 CI 和其他脚本化调用，添加 [`--bare`](#使用裸模式更快启动)，这样它们不会获取本地恰好配置的内容。

### 通过 Claude 管道传输数据

非交互模式读取 stdin，因此您可以像其他命令行工具一样管道传入数据并重定向输出。

此示例将构建日志管道传入 Claude 并将解释写入文件：

```bash theme={null}
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
```

使用 `--output-format json` 时，响应负载包含 `total_cost_usd` 和按模型的成本分解，因此脚本化调用者可以跟踪每次调用的支出而无需查看[使用量仪表板](/cn/costs)。

<Note>
  从 Claude Code v2.1.128 开始，管道 stdin 限制为 10MB。如果超过限制，Claude Code 会以明确的错误和非零状态退出。要处理更大的输入，请将内容写入文件并在提示中引用文件路径而不是管道传输。
</Note>

### 将 Claude 添加到构建脚本

您可以将非交互调用包装在脚本中，将 Claude 用作特定于项目的代码检查工具或审查工具。

此 `package.json` 脚本将与 `main` 的差异管道传入 Claude 并要求它报告拼写错误。管道传输差异意味着 Claude 不需要 Bash 权限来读取它，转义的双引号使脚本在 Windows 上可移植：

```json theme={null}
{
  "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`：带结果、会话 ID 和元数据的结构化 JSON
* `stream-json`：用于实时流式传输的换行分隔 JSON

此示例将项目摘要作为带会话元数据的 JSON 返回，文本结果在 `result` 字段中：

```bash theme={null}
claude -p "Summarize this project" --output-format json
```

要获取符合特定模式的输出，请使用 `--output-format json` 配合 `--json-schema` 和 [JSON Schema](https://json-schema.org/) 定义。响应包含请求的元数据（会话 ID、使用量等），结构化输出在 `structured_output` 字段中。

此示例提取函数名称并作为字符串数组返回：

```bash theme={null}
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"]}'
```

<Tip>
  使用 [jq](https://jqlang.github.io/jq/) 等工具解析响应并提取特定字段：

  ```bash theme={null}
  # 提取文本结果
  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'
  ```
</Tip>

### 流式传输响应

使用 `--output-format stream-json` 配合 `--verbose` 和 `--include-partial-messages` 在生成时接收令牌。每行是一个表示事件的 JSON 对象：

```bash theme={null}
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages
```

以下示例使用 [jq](https://jqlang.github.io/jq/) 过滤文本增量并仅显示流式文本。`-r` 标志输出原始字符串（无引号），`-j` 不带换行连接，使令牌连续流式传输：

```bash theme={null}
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 or null | HTTP 状态码，或对于没有 HTTP 响应的连接错误为 `null`                                                                                                                                     |
| `error`          | string          | 错误类别：`authentication_failed`、`oauth_org_not_allowed`、`billing_error`、`rate_limit`、`invalid_request`、`model_not_found`、`server_error`、`max_output_tokens` 或 `unknown`          |
| `uuid`           | string          | 唯一事件标识符                                                                                                                                                                           |
| `session_id`     | string          | 事件所属的会话                                                                                                                                                                           |

`system/init` 事件报告会话元数据，包括模型、工具、MCP 服务器和加载的插件。除非设置了 [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/cn/env-vars)，否则它是流中的第一个事件，此时 `plugin_install` 事件会在其前面。使用插件字段在插件未加载时使 CI 失败：

| 字段            | 类型  | 描述                                                                                                                                                                                                                                                                                   |
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins`       | array | 成功加载的插件，每个包含 `name` 和 `path`                                                                                                                                                                                                                                              |
| `plugin_errors` | array | 插件加载时错误，每个包含 `plugin`、`type` 和 `message`。包括未满足的依赖版本和 `--plugin-dir` 加载失败（如路径缺失或无效归档）。受影响的插件被降级且不在 `plugins` 中。没有错误时省略此键。                                                                                           |

当设置了 [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/cn/env-vars) 时，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                                                   | 事件所属的会话                                                                                         |

有关带回调和消息对象的编程流式传输，请参阅 Agent SDK 文档中的[实时流式传输响应](/cn/agent-sdk/streaming-output)。

### 自动批准工具

使用 `--allowedTools` 让 Claude 无需提示即可使用某些工具。此示例运行测试套件并修复失败，允许 Claude 执行 Bash 命令和读取/编辑文件而无需请求权限：

```bash theme={null}
claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"
```

要为整个会话设置基线而不是列出单个工具，请传递[权限模式](/cn/permission-modes)。`dontAsk` 拒绝不在您的 `permissions.allow` 规则或[只读命令集](/cn/permissions#只读命令)中的任何内容，这对于受限制的 CI 运行很有用。`acceptEdits` 让 Claude 无需提示即可写入文件，还自动批准常见的文件系统命令如 `mkdir`、`touch`、`mv` 和 `cp`。其他 shell 命令和网络请求仍然需要 `--allowedTools` 条目或 `permissions.allow` 规则，否则尝试时运行会中止：

```bash theme={null}
claude -p "Apply the lint fixes" --permission-mode acceptEdits
```

### 创建提交

此示例审查暂存的更改并创建带有适当消息的提交：

```bash theme={null}
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` 标志使用[权限规则语法](/cn/settings#权限规则语法)。尾随的 ` *` 启用前缀匹配，因此 `Bash(git diff *)` 允许任何以 `git diff` 开头的命令。`*` 前的空格很重要：没有它，`Bash(git diff*)` 也会匹配 `git diff-index`。

<Note>
  用户调用的[技能](/cn/skills)如 `/commit` 和[内置命令](/cn/commands)仅在交互模式下可用。在 `-p` 模式下，请描述您想要完成的任务。
</Note>

### 自定义系统提示

使用 `--append-system-prompt` 添加指令同时保持 Claude Code 的默认行为。此示例将 PR 差异管道传入 Claude 并指示它审查安全漏洞：

```bash theme={null}
gh pr diff "$1" | claude -p \
  --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
  --output-format json
```

有关更多选项（包括完全替换默认提示的 `--system-prompt`），请参阅[系统提示标志](/cn/cli-reference#系统提示标志)。

### 继续对话

使用 `--continue` 继续最近的对话，或使用 `--resume` 配合会话 ID 继续特定对话。此示例运行审查，然后发送后续提示：

```bash theme={null}
# 第一个请求
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 以恢复特定对话：

```bash theme={null}
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
```

## 后续步骤

* [Agent SDK 快速入门](/cn/agent-sdk/quickstart)：使用 Python 或 TypeScript 构建您的第一个代理
* [CLI 参考](/cn/cli-reference)：所有 CLI 标志和选项
* [GitHub Actions](/cn/github-actions)：在 GitHub 工作流中使用 Agent SDK
* [GitLab CI/CD](/cn/gitlab-ci-cd)：在 GitLab 流水线中使用 Agent SDK
