Claude Code 最佳实践 - Claude Code 文档
Best Practices for Claude Code - Claude Code Docs
Anthropic 文档介绍 Claude Code 最佳实践,围绕 context window 管理、Plan Mode、验证测试、CLAUDE.md、permissions、CLI、MCP servers、hooks、skills、subagents、plugins,以及 non-interactive mode、parallel sessions、auto mode 等自动化用法。
Claude Code 最佳实践 - Claude Code 文档
](https://www.anthropic.com/docs/en/overview)
English
搜索...
⌘K 询问 AI
搜索...
导航
使用 Claude Code
Claude Code 最佳实践
入门使用 Claude Code 构建管理配置参考Agent SDK最新内容资源
入门
核心概念
使用 Claude Code
平台和集成
- 概览
- Remote Control
- 网页版 Claude Code
- 桌面版 Claude Code
- Chrome extension(beta)
- Computer use(preview)
- Visual Studio Code
- JetBrains IDEs
- Code review & CI/CD
- Slack 中的 Claude Code
本页内容
- 给 Claude 一种验证其工作的方式
- 先探索,再计划,然后编码
- 在 prompt 中提供具体 context
- 提供丰富内容
- 配置你的环境
- 编写有效的 CLAUDE.md
- 配置权限
- 使用 CLI 工具
- 连接 MCP servers
- 设置 hooks
- 创建 skills
- 创建自定义 subagents
- 安装 plugins
- 有效沟通
- 询问 codebase 问题
- 让 Claude 采访你
- 管理你的 session
- 尽早且经常纠偏
- 主动管理 context
- 使用 subagents 进行调查
- 用 checkpoints 回退
- 恢复 conversations
- 自动化和扩展
- 运行 non-interactive mode
- 运行多个 Claude sessions
- 跨文件扇出
- 使用 auto mode 自主运行
- 避免常见失败模式
- 培养你的直觉
- 相关资源
使用 Claude Code
Claude Code 最佳实践
复制页面
从配置环境到跨 parallel sessions 扩展,帮助你充分利用 Claude Code 的技巧和模式。
复制页面
文档索引
在此获取完整文档索引:https://code.claude.com/docs/llms.txt
在继续探索之前,使用此文件发现所有可用页面。
Claude Code 是一个 agentic coding environment。不同于回答问题后等待的 chatbot,Claude Code 可以读取你的文件、运行命令、进行修改,并在你观察、重定向或完全离开时自主处理问题。这会改变你的工作方式。你不再是自己写代码再让 Claude review,而是描述你想要什么,Claude 会弄清楚如何构建它。Claude 会探索、计划并实现。但这种自主性仍然有学习曲线。Claude 在一些你需要理解的约束下工作。本指南涵盖了在 Anthropic 内部团队,以及在不同 codebases、语言和环境中使用 Claude Code 的工程师那里被证明有效的模式。关于 agentic loop 在底层如何工作,请参阅 Claude Code 的工作原理。
多数最佳实践都基于一个约束:Claude 的 context window 会很快填满,而随着它被填满,性能会下降。Claude 的 context window 包含你的整个 conversation,包括每条消息、Claude 读取的每个文件,以及每条命令输出。不过,它可能很快被填满。一次 debugging session 或 codebase 探索可能会生成并消耗数万 tokens。这一点很重要,因为 LLM 性能会随着 context 填满而下降。当 context window 快满时,Claude 可能开始“忘记”早先的指令,或犯更多错误。context window 是最重要的管理资源。要了解 session 在实践中如何填满,请观看交互式演示,了解启动时加载了什么,以及每次文件读取的成本。使用 custom status line 持续跟踪 context 使用情况,并参阅 Reduce token usage 获取减少 token 使用量的策略。
给 Claude 一种验证其工作的方式
包含 tests、screenshots 或预期输出,让 Claude 可以自查。这是你能做的杠杆最高的一件事。
当 Claude 能验证自己的工作时,表现会显著更好,例如运行 tests、比较 screenshots、验证输出。没有清晰的成功标准时,它可能产出看起来正确但实际上不能工作的东西。你会成为唯一的反馈回路,每个错误都需要你关注。
| 策略 | Before | After |
|---|---|---|
| 提供验证标准 | ”implement a function that validates email addresses" | "write a validateEmail function. example test cases: user@example.com is true, invalid is false, user@.com is false. run the tests after implementing” |
| 可视化验证 UI 变更 | ”make the dashboard look better" | "[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them” |
| 处理根因,而不是症状 | ”the build is failing" | "the build fails with this error: [paste error]. fix it and verify the build succeeds. address the root cause, don’t suppress the error” |
UI 变更可以使用 Claude in Chrome extension 验证。它会在你的浏览器中打开新 tabs,测试 UI,并迭代直到代码可用。你的验证也可以是 test suite、linter,或检查输出的 Bash 命令。投入精力让你的验证非常可靠。
先探索,再计划,然后编码
将研究和计划与实现分开,避免解决错误的问题。
让 Claude 直接开始编码可能会产出解决了错误问题的代码。使用 Plan Mode 将探索与执行分离。推荐工作流有四个阶段:
1
探索
进入 Plan Mode。Claude 会读取文件并回答问题,但不会进行修改。
claude (Plan Mode)
read /src/auth and understand how we handle sessions and login.
also look at how we manage environment variables for secrets.
2
计划
让 Claude 创建详细的实现计划。
claude (Plan Mode)
I want to add Google OAuth. What files need to change?
What's the session flow? Create a plan.
按 Ctrl+G 在你的文本编辑器中打开计划,以便在 Claude 继续之前直接编辑。
3
实现
切回 Normal Mode,让 Claude 编码,并对照其计划进行验证。
claude (Normal Mode)
implement the OAuth flow from your plan. write tests for the
callback handler, run the test suite and fix any failures.
4
提交
让 Claude 用描述性的消息 commit 并创建 PR。
claude (Normal Mode)
commit with a descriptive message and open a PR
Plan Mode 很有用,但也会增加开销。对于范围明确且修复很小的任务(如修正 typo、添加一行 log,或重命名变量),直接让 Claude 去做即可。当你不确定方法、变更会修改多个文件,或你不熟悉要修改的代码时,计划最有用。如果你能用一句话描述 diff,就跳过计划。
在 prompt 中提供具体 context
你的指令越精确,需要的修正就越少。
Claude 可以推断意图,但不能读心。引用具体文件,说明约束,并指向示例模式。
| 策略 | Before | After |
|---|---|---|
| 限定任务范围。 指定哪个文件、什么场景,以及测试偏好。 | ”add tests for foo.py" | "write a test for foo.py covering the edge case where the user is logged out. avoid mocks.” |
| 指向来源。 引导 Claude 去看能回答问题的来源。 | ”why does ExecutionFactory have such a weird api?" | "look through ExecutionFactory’s git history and summarize how its api came to be” |
| 引用现有模式。 指向 codebase 中的模式。 | ”add a calendar widget" | "look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase.” |
| 描述症状。 提供症状、可能位置,以及“修复后”应是什么样。 | ”fix the login bug" | "users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it” |
当你在探索且可以接受纠偏时,模糊 prompt 也可能有用。像 "what would you improve in this file?" 这样的 prompt 可能会暴露出你没想到要问的问题。
提供丰富内容
使用 @ 引用文件、粘贴 screenshots/images,或直接 pipe 数据。
你可以通过几种方式向 Claude 提供丰富数据:
- 用
@引用文件,而不是描述代码在哪里。Claude 会在回答前读取文件。 - 直接粘贴图片。将图片复制/粘贴或拖放到 prompt 中。
- 提供 URLs,用于文档和 API references。使用
/permissionsallowlist 常用域名。 - pipe 数据,通过运行
cat error.log | claude直接发送文件内容。 - 让 Claude 获取它需要的内容。告诉 Claude 使用 Bash 命令、MCP tools 或读取文件来自行拉取 context。
配置你的环境
少量设置步骤可以显著提升 Claude Code 在所有 sessions 中的效果。关于 extension 功能以及何时使用每一种的完整概览,请参阅 扩展 Claude Code。
编写有效的 CLAUDE.md
运行 /init,基于当前项目结构生成一个初始 CLAUDE.md 文件,然后随时间完善。
CLAUDE.md 是一个特殊文件,Claude 会在每次 conversation 开始时读取它。包含 Bash 命令、代码风格和工作流规则。这会给 Claude 提供无法仅从代码中推断出的持久 context。/init 命令会分析你的 codebase,检测 build systems、test frameworks 和代码模式,为你提供一个可继续完善的坚实基础。CLAUDE.md 文件没有必需格式,但应保持简短、易读。例如:
CLAUDE.md
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')
# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance
CLAUDE.md 每个 session 都会加载,所以只包含普遍适用的内容。对于只在某些时候相关的领域知识或工作流,请改用 skills。Claude 会按需加载它们,而不会让每个 conversation 膨胀。保持简洁。对每一行都问自己:“删除这一行会导致 Claude 犯错吗?” 如果不会,就删掉。臃肿的 CLAUDE.md 文件会导致 Claude 忽略你的实际指令!
| ✅ 包含 | ❌ 排除 |
|---|---|
| Claude 无法猜到的 Bash 命令 | Claude 通过读取代码即可弄清楚的任何内容 |
| 不同于默认值的代码风格规则 | Claude 已经知道的标准语言约定 |
| 测试指令和偏好的 test runners | 详细 API 文档(改为链接到文档) |
| Repository 规矩(branch 命名、PR 约定) | 频繁变化的信息 |
| 项目特定的架构决策 | 冗长解释或教程 |
| 开发环境怪癖(必需的 env vars) | codebase 的逐文件描述 |
| 常见陷阱或不明显行为 | “write clean code” 这类不言自明的实践 |
如果 Claude 一直做你不想要的事,尽管文件中已有反对规则,那文件可能太长,规则被淹没了。如果 Claude 问了 CLAUDE.md 中已经回答的问题,措辞可能有歧义。把 CLAUDE.md 当作代码:出问题时 review 它,定期修剪它,并通过观察 Claude 行为是否实际变化来测试改动。你可以通过添加强调(例如 “IMPORTANT” 或 “YOU MUST”)来调优指令,提高遵循度。将 CLAUDE.md 提交到 git,让你的团队可以共同贡献。这个文件会随时间积累价值。CLAUDE.md 文件可以使用 @path/to/import 语法导入其他文件:
CLAUDE.md
See @README.md for project overview and @package.json for available npm commands.
# Additional Instructions
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.md
你可以将 CLAUDE.md 文件放在多个位置:
- Home folder (
~/.claude/CLAUDE.md):适用于所有 Claude sessions - Project root (
./CLAUDE.md):提交到 git,与团队共享 - Project root (
./CLAUDE.local.md):个人项目特定笔记;将此文件加入.gitignore,避免与团队共享 - Parent directories:适用于 monorepos,
root/CLAUDE.md和root/foo/CLAUDE.md都会被自动拉入 - Child directories:当处理这些目录中的文件时,Claude 会按需拉入子目录中的 CLAUDE.md 文件
配置权限
使用 auto mode 让 classifier 处理 approvals,使用 /permissions allowlist 特定命令,或使用 /sandbox 进行 OS-level 隔离。每种方式都能减少中断,同时让你保持控制。
默认情况下,Claude Code 会对可能修改系统的操作请求权限:文件写入、Bash 命令、MCP tools 等。这很安全,但很繁琐。第十次 approval 之后,你其实已经不再认真 review,只是在一路点击。有三种方式可以减少这些中断:
- Auto mode:一个单独的 classifier model 会 review 命令,并只阻止看起来有风险的命令:scope escalation、未知基础设施,或由 hostile content 驱动的操作。当你信任任务的大致方向但不想逐步点击时最适合
- Permission allowlists:允许你知道安全的特定 tools,例如
npm run lint或git commit - Sandboxing:启用 OS-level 隔离,限制 filesystem 和 network 访问,使 Claude 能在定义好的边界内更自由地工作
进一步阅读 permission modes、permission rules 和 sandboxing。
使用 CLI 工具
告诉 Claude Code 在与外部服务交互时使用 gh、aws、gcloud 和 sentry-cli 等 CLI 工具。
CLI 工具是与外部服务交互时最节省 context 的方式。如果你使用 GitHub,安装 gh CLI。Claude 知道如何用它创建 issues、打开 pull requests 和读取 comments。没有 gh 时,Claude 仍可以使用 GitHub API,但未认证请求通常会遇到 rate limits。Claude 也很擅长学习它尚不知道的 CLI 工具。尝试这样的 prompt:Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.
连接 MCP servers
运行 claude mcp add 连接外部工具,例如 Notion、Figma 或你的数据库。
借助 MCP servers,你可以让 Claude 根据 issue trackers 实现功能、查询数据库、分析 monitoring data、集成 Figma 设计,并自动化 workflows。
设置 hooks
对必须每次无例外执行的操作使用 hooks。
Hooks 会在 Claude 工作流的特定节点自动运行 scripts。不同于 CLAUDE.md 中的指导性指令,hooks 是确定性的,并保证动作发生。Claude 可以为你编写 hooks。尝试这样的 prompt:“Write a hook that runs eslint after every file edit” 或 “Write a hook that blocks writes to the migrations folder.” 直接编辑 .claude/settings.json 以手动配置 hooks,并运行 /hooks 浏览已配置内容。
创建 skills
在 .claude/skills/ 中创建 SKILL.md 文件,为 Claude 提供领域知识和可复用工作流。
Skills 用特定于你的项目、团队或领域的信息扩展 Claude 的知识。Claude 会在相关时自动应用它们,或者你可以用 /skill-name 直接调用。通过向 .claude/skills/ 添加带有 SKILL.md 的目录来创建 skill:
.claude/skills/api-conventions/SKILL.md
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in the URL path (/v1/, /v2/)
Skills 也可以定义你直接调用的可重复工作流:
.claude/skills/fix-issue/SKILL.md
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PR
运行 /fix-issue 1234 调用它。对于你想手动触发且有副作用的工作流,使用 disable-model-invocation: true。
创建自定义 subagents
在 .claude/agents/ 中定义专门的 assistants,Claude 可以把隔离任务委托给它们。
Subagents 在自己的 context 中运行,并拥有自己的 allowed tools 集合。它们适合需要读取很多文件,或需要专门关注但不想污染主 conversation 的任务。
.claude/agents/security-reviewer.md
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling
Provide specific line references and suggested fixes.
明确告诉 Claude 使用 subagents:“Use a subagent to review this code for security issues.”
安装 plugins
运行 /plugin 浏览 marketplace。Plugins 无需配置即可添加 skills、tools 和 integrations。
Plugins 将来自社区和 Anthropic 的 skills、hooks、subagents 和 MCP servers 打包成一个可安装单元。如果你使用 typed language,请安装 code intelligence plugin,为 Claude 提供精确的 symbol navigation 和编辑后的自动错误检测。关于如何在 skills、subagents、hooks 和 MCP 之间选择,请参阅 扩展 Claude Code。
有效沟通
你与 Claude Code 沟通的方式会显著影响结果质量。
询问 codebase 问题
向 Claude 提出你会问资深工程师的问题。
在熟悉新的 codebase 时,使用 Claude Code 进行学习和探索。你可以向 Claude 提出与向其他工程师提问相同类型的问题:
- Logging 是如何工作的?
- 我如何创建一个新的 API endpoint?
foo.rs第 134 行的async move { ... }是什么意思?CustomerOnboardingFlowImpl处理了哪些 edge cases?- 为什么这段代码在第 333 行调用
foo()而不是bar()?
以这种方式使用 Claude Code 是一种有效的 onboarding workflow,可以缩短上手时间,并减少其他工程师的负担。不需要特殊 prompting:直接提问即可。
让 Claude 采访你
对于较大的功能,让 Claude 先采访你。从一个最小 prompt 开始,并要求 Claude 使用 AskUserQuestion tool 采访你。
Claude 会询问你可能尚未考虑的问题,包括技术实现、UI/UX、edge cases 和取舍。
I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.
Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
spec 完成后,开启一个新的 session 来执行它。新 session 有干净的 context,完全聚焦于实现,并且你有一份可引用的书面 spec。
管理你的 session
Conversations 是持久且可回退的。利用这一点!
尽早且经常纠偏
一旦发现 Claude 偏离轨道,就立即纠正。
最佳结果来自紧密反馈回路。虽然 Claude 偶尔能在第一次尝试中完美解决问题,但快速纠正通常能更快地产生更好的解决方案。
Esc:用Esc键在动作中途停止 Claude。Context 会保留,因此你可以重定向。Esc + Esc或/rewind:按两次Esc或运行/rewind打开 rewind 菜单,恢复先前的 conversation 和代码状态,或从选定消息开始摘要。"Undo that":让 Claude 回滚它的更改。/clear:在无关任务之间重置 context。带有无关 context 的长 sessions 可能会降低性能。
如果你在一个 session 中针对同一问题纠正 Claude 超过两次,context 就已经被失败方法污染。运行 /clear,用一个更具体、整合你已学到内容的 prompt 重新开始。带有更好 prompt 的干净 session 几乎总是优于累积了大量修正的长 session。
主动管理 context
在无关任务之间运行 /clear 来重置 context。
当接近 context limits 时,Claude Code 会自动 compact conversation history,在释放空间的同时保留重要代码和决策。在长 sessions 中,Claude 的 context window 可能会填满无关的 conversation、文件内容和命令。这会降低性能,有时还会分散 Claude 的注意力。
- 在任务之间频繁使用
/clear,完全重置 context window - 当 auto compaction 触发时,Claude 会总结最重要的内容,包括代码模式、文件状态和关键决策
- 如需更多控制,运行
/compact <instructions>,例如/compact Focus on the API changes - 如果只想 compact conversation 的一部分,使用
Esc + Esc或/rewind,选择一个 message checkpoint,然后选择 Summarize from here。这会压缩从该点往后的消息,同时保留之前的 context。 - 在 CLAUDE.md 中用类似
"When compacting, always preserve the full list of modified files and any test commands"的指令自定义 compaction 行为,确保关键 context 在摘要中保留下来 - 对于不需要留在 context 中的快速问题,使用
/btw。答案会显示在可关闭的 overlay 中,并且不会进入 conversation history,因此你可以检查细节而不增加 context。
使用 subagents 进行调查
用 "use subagents to investigate X" 委托研究。它们会在单独的 context 中探索,让你的主 conversation 保持干净,以便实现。
由于 context 是你的根本约束,subagents 是最强大的可用工具之一。当 Claude 研究 codebase 时,它会读取大量文件,而这些都会消耗你的 context。Subagents 在独立的 context windows 中运行,并返回摘要:
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
subagent 会探索 codebase、读取相关文件并返回发现,所有这些都不会污染你的主 conversation。你也可以在 Claude 实现某些内容后使用 subagents 进行验证:
use a subagent to review this code for edge cases
用 checkpoints 回退
Claude 的每个动作都会创建一个 checkpoint。你可以将 conversation、代码或两者恢复到任何先前 checkpoint。
Claude 会在更改前自动 checkpoint。双击 Escape 或运行 /rewind 打开 rewind 菜单。你可以只恢复 conversation、只恢复代码、两者都恢复,或从选定消息开始摘要。详情请参阅 Checkpointing。你可以告诉 Claude 尝试一些有风险的事情,而不是仔细规划每一步。如果它不起作用,就 rewind 并尝试不同方法。Checkpoints 会跨 sessions 保留,因此你可以关闭 terminal,稍后仍然回退。
Checkpoints 只跟踪 Claude 所做的更改,而不是外部进程。这不能替代 git。
恢复 conversations
运行 claude --continue 从上次中断处继续,或运行 --resume 从最近 sessions 中选择。
Claude Code 会在本地保存 conversations。当一个任务跨越多个 sessions 时,你不必重新解释 context:
claude --continue # Resume the most recent conversation
claude --resume # Select from recent conversations
使用 /rename 为 sessions 起描述性名称,例如 "oauth-migration" 或 "debugging-memory-leak",方便日后查找。把 sessions 当作 branches:不同 workstreams 可以有各自独立、持久的 contexts。
自动化和扩展
一旦你能有效使用一个 Claude,就通过 parallel sessions、non-interactive mode 和 fan-out patterns 放大产出。到目前为止,所有内容都假设一个人、一个 Claude、一个 conversation。但 Claude Code 可以横向扩展。本节的技巧展示了如何完成更多工作。
运行 non-interactive mode
在 CI、pre-commit hooks 或 scripts 中使用 claude -p "prompt"。添加 --output-format stream-json 可获得 streaming JSON 输出。
使用 claude -p "your prompt",你可以以非交互方式运行 Claude,而无需 session。Non-interactive mode 是将 Claude 集成到 CI pipelines、pre-commit hooks 或任何自动化工作流中的方式。输出格式允许你以程序方式解析结果:plain text、JSON 或 streaming JSON。
# One-off queries
claude -p "Explain what this project does"
# Structured output for scripts
claude -p "List all API endpoints" --output-format json
# Streaming for real-time processing
claude -p "Analyze this log file" --output-format stream-json
运行多个 Claude sessions
并行运行多个 Claude sessions,以加快开发、运行隔离实验,或启动复杂工作流。
运行 parallel sessions 主要有三种方式:
- Claude Code desktop app:以可视方式管理多个本地 sessions。每个 session 都有自己的隔离 worktree。
- 网页版 Claude Code:在 Anthropic 的安全云基础设施中的隔离 VMs 上运行。
- Agent teams:通过共享任务、消息和 team lead 自动协调多个 sessions。
除了并行化工作,多个 sessions 还能支持以质量为中心的工作流。新的 context 能改善 code review,因为 Claude 不会偏向于它刚写的代码。例如,使用 Writer/Reviewer 模式:
| Session A (Writer) | Session B (Reviewer) |
|---|---|
Implement a rate limiter for our API endpoints |
|
Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns. |
|
Here's the review feedback: [Session B output]. Address these issues. |
你也可以用 tests 做类似事情:让一个 Claude 写 tests,再让另一个写通过这些 tests 的代码。
跨文件扇出
循环任务并为每个任务调用 claude -p。使用 --allowedTools 为批量操作限定权限范围。
对于大型迁移或分析,你可以将工作分发到许多并行 Claude 调用:
1
生成任务列表
让 Claude 列出所有需要迁移的文件(例如 list all 2,000 Python files that need migrating)
2
编写脚本遍历列表
for file in $(cat files.txt); do
claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
--allowedTools "Edit,Bash(git commit *)"
done
3
先在少量文件上测试,再规模化运行
根据前 2-3 个文件出错情况优化 prompt,然后在完整集合上运行。--allowedTools flag 会限制 Claude 能做什么,这在无人值守运行时很重要。
你也可以将 Claude 集成到现有 data/processing pipelines 中:
claude -p "<your prompt>" --output-format json | your_command
开发期间使用 --verbose 进行 debugging,生产环境中关闭它。
使用 auto mode 自主运行
如需在后台安全检查下不中断执行,请使用 auto mode。classifier model 会在命令运行前 review 命令,阻止 scope escalation、未知基础设施和由 hostile content 驱动的操作,同时让常规工作无需 prompt 即可继续。
claude --permission-mode auto -p "fix all lint errors"
对于带 -p flag 的 non-interactive 运行,如果 classifier 反复阻止操作,auto mode 会中止,因为没有用户可回退。阈值请参阅 when auto mode falls back。
避免常见失败模式
这些是常见错误。尽早识别它们可以节省时间:
- The kitchen sink session。 你从一个任务开始,然后问 Claude 一些无关内容,接着又回到第一个任务。Context 里充满无关信息。
修复:在无关任务之间使用
/clear。
- 反复纠正。 Claude 做错了,你纠正它,它仍然错,你再纠正。Context 被失败方法污染。
修复:两次纠正失败后,
/clear,并写一个更好的初始 prompt,融入你学到的内容。
- 过度指定的 CLAUDE.md。 如果你的 CLAUDE.md 太长,Claude 会忽略其中一半,因为重要规则淹没在噪声中。
修复:严格修剪。如果 Claude 在没有指令时已经能正确做某件事,删除该指令,或将其转换为 hook。
- 信任后验证的缺口。 Claude 产出一个看起来合理、但没有处理 edge cases 的实现。
修复:始终提供验证(tests、scripts、screenshots)。如果你无法验证,就不要发布。
- 无限探索。 你让 Claude “investigate” 某事,却没有限定范围。Claude 读取数百个文件,填满 context。
修复:缩小调查范围,或使用 subagents,让探索不要消耗你的主 context。
培养你的直觉
本指南中的模式并非一成不变。它们是通常效果不错的起点,但未必适合每种情况。有时你 应该 让 context 累积,因为你正深入一个复杂问题,而历史记录很有价值。有时你应该跳过计划,让 Claude 自己弄清楚,因为任务是探索性的。有时模糊 prompt 正合适,因为你想先看看 Claude 如何解释问题,再施加约束。关注什么有效。当 Claude 产出优秀结果时,留意你做了什么:prompt 结构、你提供的 context、你所处的 mode。当 Claude 遇到困难时,追问原因。Context 是否太嘈杂?Prompt 是否太模糊?任务是否太大,无法一次完成?随着时间推移,你会培养出任何指南都无法完全捕捉的直觉。你会知道何时具体、何时开放,何时计划、何时探索,何时清空 context、何时让它累积。
相关资源
- Claude Code 的工作原理:agentic loop、tools 和 context management
- 扩展 Claude Code:skills、hooks、MCP、subagents 和 plugins
- 常见工作流:debugging、testing、PRs 等的分步做法
- CLAUDE.md:存储项目约定和持久 context
这个页面有帮助吗?
是 否
⌘I
公司
Anthropic招聘Economic Futures研究新闻Trust center透明度
帮助和安全
学习
课程MCP connectors客户案例工程博客活动Powered by Claude服务合作伙伴Startups program
条款和政策
Assistant
Responses are generated using AI and may contain mistakes.