在终端里用 GitHub Copilot CLI 规划、编写和审查 Python 代码

2026-06-29 28 预计阅读时间: 1 分钟
来源: realpython.com AI 摘要 Original link

Disclaimer: This article is an AI-assisted summary. Read it together with the original source when precision matters. The summary may omit context, version differences, or edge cases and is not official documentation.

预计阅读时间:8 分钟

GitHub Copilot 不再只是编辑器里的补全按钮。Copilot CLI 把 AI agent 带进终端,让你可以在命令行里完成安装、认证、任务规划、代码生成和代码审查。对经常在 shell、Git、Python 项目之间切换的开发者来说,这意味着少了一次上下文切换,多了一个可以直接参与开发流程的助手。

它适合解决什么问题

Copilot CLI 的关键变化不是“能聊天”,而是它贴近开发者每天已经在用的工作面:终端。

你可以把它用于三类任务:

  • 规划:把一个模糊需求拆成可执行步骤,例如“为这个 Python 包增加输入校验和测试”。
  • 编写:让 agent 根据当前目录、文件结构和你的指令生成代码。
  • 审查:让它检查 diff、指出潜在 bug、测试缺口或风格问题。

这类工具尤其适合小到中等规模的改动。比如修一个 CLI 参数解析问题、补一组单元测试、解释某段 Python 逻辑为什么失败。它不适合在无人监督下重写核心业务模块,也不应该替代代码评审和测试。

安装与认证:先把终端接上 Copilot

具体安装方式会随 GitHub CLI 和 Copilot CLI 的发布节奏变化,实际使用时应以你本机 gh 和 GitHub 官方文档为准。可以这样实践:先确认 GitHub CLI 可用,再安装 Copilot 相关扩展并完成认证。

# 1. 确认 GitHub CLI 已安装
gh --version

# 2. 登录 GitHub,按提示在浏览器中授权
gh auth login

# 3. 安装 Copilot CLI/扩展能力
# 如果你的环境使用 gh 扩展,可以尝试:
gh extension install github/gh-copilot

# 4. 查看可用命令
gh copilot --help

如果你在公司网络或受管设备上使用,还要确认这几件事:

  • GitHub Copilot 订阅或组织授权已经开通。
  • 终端能访问 GitHub 相关服务。
  • 组织策略允许在当前仓库使用 Copilot。
  • 不要把密钥、客户数据、未脱敏日志直接粘进提示词。

从一个 Python 小项目开始

假设我们有一个简单需求:写一个函数,把字符串列表规整为小写、去空白、去重,并保留首次出现顺序。我们可以先搭一个最小项目,再让 Copilot CLI 辅助规划和实现。

mkdir copilot-cli-demo
cd copilot-cli-demo
python -m venv .venv
source .venv/bin/activate
python -m pip install pytest
mkdir -p src tests
printf '' > src/text_utils.py
printf '' > tests/test_text_utils.py

接下来可以让 Copilot 在终端里帮你规划。不同版本的命令参数可能略有差异,下面示例展示的是工作方式:把任务描述清楚、要求它考虑测试和边界条件。

gh copilot suggest "Plan a small Python change: implement normalize_tags(items) in src/text_utils.py. It should trim whitespace, lowercase values, remove empty strings, deduplicate while preserving order, and include pytest tests."

如果你的 Copilot CLI 支持 agent 式编辑,也可以把需求写得更明确:

gh copilot suggest "Write the Python implementation and pytest tests for normalize_tags(items). Keep the function small, type-hinted, and raise TypeError if items is not iterable."

工具给出的结果不要直接盲信。更稳的做法是让它生成方案或补丁,然后你检查文件、运行测试、再提交。

可以落地的一份 Python 实现

即使不用 Copilot 自动写文件,也可以把下面这份代码作为目标实现,让 Copilot CLI 帮你解释、改进或审查。

src/text_utils.py

from collections.abc import Iterable


def normalize_tags(items: Iterable[str]) -> list[str]:
    """Normalize tags by trimming, lowercasing, and removing duplicates."""
    if isinstance(items, (str, bytes)) or not isinstance(items, Iterable):
        raise TypeError("items must be an iterable of strings")

    seen: set[str] = set()
    result: list[str] = []

    for item in items:
        if not isinstance(item, str):
            raise TypeError("all items must be strings")

        value = item.strip().lower()
        if not value or value in seen:
            continue

        seen.add(value)
        result.append(value)

    return result

tests/test_text_utils.py

import pytest

from src.text_utils import normalize_tags


def test_normalize_tags_trims_lowercases_and_deduplicates():
    assert normalize_tags([" Python ", "python", "CLI", " cli ", ""]) == [
        "python",
        "cli",
    ]


def test_normalize_tags_preserves_first_seen_order():
    assert normalize_tags(["B", "a", "b", "A", "c"]) == ["b", "a", "c"]


def test_normalize_tags_rejects_plain_string():
    with pytest.raises(TypeError):
        normalize_tags("python")


def test_normalize_tags_rejects_non_string_items():
    with pytest.raises(TypeError):
        normalize_tags(["python", 3])

运行测试:

python -m pytest -q

然后让 Copilot CLI 审查当前改动,可以这样问:

git diff -- src tests

gh copilot suggest "Review this Python change for correctness, edge cases, and missing tests. Focus on normalize_tags and pytest coverage."

如果工具无法自动读取 diff,就把 git diff 的输出作为上下文粘给它,或者使用你当前版本支持的 review/agent 子命令。

写提示词时要像写工单

在终端里使用 Copilot CLI,提示词越像工程任务,结果越可用。不要只写“帮我优化代码”,而是说明约束、文件、验收标准和风险点。

一个更好的提示词可以这样写:

You are working in a small Python project.
Task: implement normalize_tags(items) in src/text_utils.py and add pytest tests in tests/test_text_utils.py.
Requirements:
- Trim whitespace and lowercase each tag.
- Drop empty values.
- Deduplicate while preserving first-seen order.
- Reject a plain string input with TypeError.
- Reject non-string items with TypeError.
- Keep implementation dependency-free.
After editing, explain the edge cases covered by tests.

这种写法给 agent 足够上下文,也方便你验收。它把“生成代码”变成“完成一个可测试的改动”。

采用建议:让 CLI agent 进入流程,但别绕过流程

Copilot CLI 的价值在于把 AI 辅助放到开发链路里:打开终端、描述任务、生成方案、修改代码、跑测试、审查 diff。它可以加快小改动和探索性工作,但边界也很明确。

落地时可以按这个清单执行:

  • 从非核心模块、小函数、测试补全开始试用。
  • 每次让它改动前,先要求输出计划。
  • 对生成代码运行本地测试和格式化工具。
  • 对涉及安全、权限、计费、数据删除的改动保持人工审查。
  • 不把密钥、生产日志、客户数据作为提示词输入。
  • 把 Copilot 的输出当作候选补丁,而不是最终答案。

终端里的 AI agent 最适合做“结对时的第二双眼睛”:它能给你草图、补样板、提醒遗漏,但提交到主干之前,仍然要由测试、审查和工程判断把关。


相关推荐