📚 入门教程
什么是 Claude Code?
Claude Code 是 Anthropic 官方推出的命令行 AI 编程助手。它基于强大的 Claude 模型, 能够深度理解你的代码库,执行复杂的编码任务,包括创建新功能、修复 Bug、 重构代码、编写测试等。
与其他 AI 编码工具相比,Claude Code 的优势在于:
- 深度代码理解:能够阅读和理解整个代码库
- 安全执行:在执行敏感操作前会请求确认
- 工具集成:支持 MCP 协议,可连接外部工具
- 多模型支持:支持 Claude 3.5、3.7、4 等多个模型
安装 Claude Code
系统要求
- Node.js 18+
- macOS、Linux 或 Windows (WSL)
- Anthropic API Key 或 Claude Pro 订阅
使用 npm 安装
终端
1
npm install -g @anthropic-ai/claude-code验证安装
终端
1
claude --version认证配置
方式一:使用 API Key
终端
1
2
3
4
5
# 设置环境变量
export ANTHROPIC_API_KEY="your-api-key-here"
# 或者让 Claude Code 引导你设置
claude方式二:使用 Claude Pro
如果你有 Claude Pro 订阅,可以直接通过浏览器登录认证:
终端
1
claude首次运行时会提示你登录,按提示完成浏览器认证即可。
基础命令
启动交互式会话
终端
1
2
3
4
5
# 在当前目录启动
claude
# 指定工作目录
claude --cd /path/to/project一次性执行任务
终端
1
2
3
4
5
# 使用 --print 模式执行单个任务
claude --print "创建一个 Python Flask Hello World 应用"
# 继续上一次会话
claude --continue常用参数
| 参数 | 说明 |
|---|---|
| 非交互模式,执行后退出 | |
| --continue | 继续上一次会话 |
| --model | 指定模型 (claude-3-5-sonnet, claude-4 等) |
| --help | 显示帮助信息 |
第一个项目
让我们创建一个简单的 Python 项目来体验 Claude Code 的能力:
终端
1
2
3
4
5
6
7
8
9
# 创建项目目录
mkdir my-first-project
cd my-first-project
# 初始化 git (推荐)
git init
# 启动 Claude Code
claude然后在 Claude Code 中输入:
Claude Code 提示
1
2
3
4
5
6
7
创建一个简单的待办事项 CLI 应用,使用 Python,功能包括:
1. 添加待办事项
2. 列出所有待办事项
3. 标记完成
4. 删除待办事项
使用 JSON 文件存储数据。Claude Code 会自动创建项目结构、编写代码、甚至帮你测试。 如果需要确认某些操作(如创建文件),它会暂停并请求你的批准。
🚀 实战项目案例
项目 1: 待办事项 CLI 应用
这是一个完整的 Python CLI 待办事项应用,演示 Claude Code 如何从零开始创建项目。
步骤 1: 创建项目
终端
1
2
3
mkdir todo-cli && cd todo-cli
git init
claude步骤 2: 描述需求
Claude Code 提示
1
2
3
4
5
创建一个 Python 待办事项 CLI 应用:
1. 使用 click 库处理命令行参数
2. 使用 JSON 文件存储数据
3. 支持 add、list、complete、delete 命令
4. 添加单元测试步骤 3: 生成的代码
todo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# todo.py
import click
import json
import os
TODO_FILE = "todos.json"
def load_todos():
if os.path.exists(TODO_FILE):
with open(TODO_FILE, "r") as f:
return json.load(f)
return []
def save_todos(todos):
with open(TODO_FILE, "w") as f:
json.dump(todos, f, indent=2)
@click.group()
def cli():
"""待办事项 CLI 应用"""
pass
@cli.command()
@click.argument("task")
def add(task):
"""添加新的待办事项"""
todos = load_todos()
todos.append({"task": task, "done": False})
save_todos(todos)
click.echo(f"✅ 已添加: {task}")
@cli.command()
def list():
"""列出所有待办事项"""
todos = load_todos()
for i, todo in enumerate(todos):
status = "✓" if todo["done"] else " "
click.echo(f"{i+1}. [{status}] {todo['task']}")
if __name__ == "__main__":
cli()运行结果
终端输出
1
2
3
4
5
6
7
$ python todo.py add "学习 Claude Code"
✅ 已添加: 学习 Claude Code
$ python todo.py add "完成项目"
✅ 已添加: 完成项目
$ python todo.py list
1. [ ] 学习 Claude Code
2. [ ] 完成项目项目 2: 天气查询 CLI
创建一个天气查询命令行工具,调用免费天气 API。
Claude Code 提示
1
2
3
4
5
创建一个天气查询 CLI:
1. 使用 requests 库调用 wttr.in API
2. 支持城市名称查询
3. 显示温度、天气状况、湿度
4. 添加 --json 参数输出 JSON 格式weather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# weather.py
import click
import requests
@click.command()
@click.argument("city")
@click.option("--json", "json_output", is_flag=True, help="输出 JSON 格式")
def weather(city, json_output):
"""查询城市天气"""
url = f"https://wttr.in/{city}?format=j1"
response = requests.get(url)
data = response.json()
current = data["current_condition"][0]
if json_output:
click.echo(response.text)
else:
click.echo(f"🏙️ {city} 天气")
click.echo(f"🌡️ 温度: {current['temp_C']}°C")
click.echo(f"☁️ 天气: {current['weatherDesc'][0]['value']}")
click.echo(f"💧 湿度: {current['humidity']}%")
if __name__ == "__main__":
weather()项目 3: GitHub 文件上传脚本
创建一个自动上传文件到 GitHub 的脚本。
Claude Code 提示
1
2
3
4
5
创建一个 GitHub 文件上传脚本:
1. 使用 PyGithub 库
2. 支持指定仓库和分支
3. 自动处理文件更新
4. 添加日志记录github_upload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# github_upload.py
from github import Github
import os
import argparse
def upload_file(token, repo_name, file_path, branch="main"):
"""上传文件到 GitHub"""
g = Github(token)
repo = g.get_repo(repo_name)
with open(file_path, "r") as f:
content = f.read()
file_name = os.path.basename(file_path)
try:
# 尝试更新现有文件
contents = repo.get_contents(file_name, ref=branch)
repo.update_file(
file_name,
f"Update {file_name}",
content,
contents.sha,
branch=branch
)
print(f"✅ 已更新: {file_name}")
except:
# 创建新文件
repo.create_file(
file_name,
f"Create {file_name}",
content,
branch=branch
)
print(f"✅ 已创建: {file_name}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--token", required=True)
parser.add_argument("--repo", required=True)
parser.add_argument("--file", required=True)
parser.add_argument("--branch", default="main")
args = parser.parse_args()
upload_file(args.token, args.repo, args.file, args.branch)💡 小贴士
- •在项目根目录运行 Claude Code,它能更好地理解项目结构
- •使用 Git 可以方便地回滚 Claude Code 的修改
- •清晰的提示会得到更好的结果,描述你想要的具体功能
- •使用 /help 命令查看内置命令