蓝色天空网mbsky.com · 知识 · 实践 · 创造Codex 教程 · 本地阅读预览
教程 / AI / 智能开发 / Codex 教程

Codex CLI 实用示例:从任务说明到可重现检查

把编码、审查、排错和文件操作写成有明确结果的任务,并在临时仓库实际核对。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

把输入、输出和兼容条件写进任务

请实现最长字符串查询时,写清返回字符串和零基索引、空列表返回什么、等长如何决定。本站用遍历保留第一个等长结果,分别测试普通列表、并列、空列表和只有一个空串。真实项目需确认字符长度与用户所见字符的定义。

请把平方列表改成生成器时,说明消费者应按迭代协议读取。用 next 取首项,再消费剩余项,最后检查耗尽与空序列。需要重复迭代、下标或长度的调用方要另外确认兼容性。

本机最长字符串、生成器与错误分支的实际观察
本站独立编写并运行练习,图中是实际程序结果。

审查一段代码,再重现问题

审查转换代码时要求给出输入和实际分支。本站例子检查缩放、加偏移及保持值。不同类型是否合理由契约决定,缺字段和未知转换应有可观察的错误。提取因子和偏移后用另一组数实测,避免只改变量名。

终端可用 /review 检查工作树,版本支持的入口以菜单及帮助为准。对于限定目录,可在要求中写路径并对照实际差异,旧 /review src/ 不宜当成跨版本保证。审查输出应指出文件、可重现条件、影响和建议。

报告网络错误时区分解析、TCP 建连、TLS、HTTP 和代理。先提供错误链和用途,减少凭据与个人数据。本站在环回端口绑定但不监听,实际得到连接失败,可能表现为拒绝或超时。类似异常只提供排查方向,根因仍需对应服务的证据。

添加日志时保持函数的正常返回,记录能支持排错的最少量数据。本站对 9、4 实测差值及结果 29,检查真实日志输出。线上级别、日志目的地和数据脱敏按环境配置。

先列出文件范围,再运行测试和 Git 操作

批量重命名可先生成源与目标列表,检查已有目标和命名冲突,再执行允许的项。本站在临时目录应用匹配条件,只重命名两个自有样例。创建 Flask 骨架时逐一确定入口、配置、依赖、静态目录、模板和测试。脚手架与真实启动是两项检查。

运行测试请给出仓库约定和命令。Python 可能用 unittest 或 pytest,Node 常见 npm test 或 yarn test,Rust 可用 cargo test。本站实际运行 unittest,检查退出码和测试结论。需要 shell 操作时可读当前 CLI 的 ! 入口,并遵循有效权限。

提交前先看 git status、git diff 和已暂存差异,按本次任务选路径。旧例 git add -A 会一次纳入广泛改动,适合明确所有文件均属于任务时使用。本站只提交三个明确的练习文件,并从 Git 返回的提交内容核对范围。

项目分析可先读依赖清单、入口和目录,再跟踪实际导入。本站核对骨架的 Python 导入路径,静态查找遇到动态加载和别名时还需运行证据。

用计划交代复杂功能的验收

认证方案可拆成数据存储、注册和登录端点、令牌签发与校验、前端状态、测试。使用 /plan 时先明确待解决的权限、错误、依赖和测试,终端确认方式随版本变化。要运行部署或发起外部动作时按任务授权。

短信或邮件验证码是另一类综合任务。明确代码为六位含前导零、重发间隔 60 秒、有效期 10 分钟,再规划过期边界、重复验证、次数限制和测试时钟。使用真实发送前核对外部依赖和授权,本站只给出需求拆分。

常用任务入口

场景请求或操作
写一个函数说明输入、输出、异常、示例及验证边界。
审查代码明确代码路径及差异,说明关注点,也可用 /review。
调试问题提供错误链、复现步骤和期望,区分不同失败阶段。
执行命令确定适用 Shell、目录和权限,可按当前终端入口执行。
复杂任务规划用 /plan 或先请求拆解,写出实施与验收目标。
理解代码请定位入口、依赖及具体调用,引用相关文件。

运行函数、复现连接失败并核对临时仓库操作

python · 阅读源码
"""Run concrete development examples in an isolated directory without contacting a model."""
from hashlib import sha256
import io
import json
import logging
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
from tempfile import TemporaryDirectory


def longest(labels):
    best = (None, -1)
    for index, label in enumerate(labels):
        if best[0] is None or len(label) > len(best[0]):
            best = (label, index)
    return best


def squares(stop):
    return (value ** 2 for value in range(stop))


def process(rows, *, factor=3, offset=4):
    handlers = {"scale": lambda value: value * factor,
                "shift": lambda value: value + offset, "keep": lambda value: value}
    return [handlers[row["mode"]](row["score"]) for row in rows]


def main():
    codex = shutil.which("codex.exe") or shutil.which("codex")
    git = shutil.which("git")
    if not codex or not git:
        raise SystemExit("Install Codex CLI and Git and add them to PATH.")
    cases = []

    def check(name, inputs, action, expected, actual):
        assert actual == expected, (name, expected, actual)
        cases.append(dict(name="cli_examples_"+name,input=inputs,operation=action,expected=expected,actual=actual))

    labels = [[], ["go","python","rust"], ["aa","bb"], [""]]
    check("longest",labels,"Call own function on ordinary, tie, empty collection and empty string cases",
          [[None,-1],["python",1],["aa",0],["",0]],[list(longest(row)) for row in labels])
    numbers = squares(5)
    check("generator",5,"Read first item, remaining values, exhaustion and empty iterator",
          [0,[1,4,9,16],[],[]],[next(numbers),list(numbers),list(numbers),list(squares(0))])
    source = [{"mode":"scale","score":2},{"mode":"shift","score":2},{"mode":"keep","score":"blue"}]
    check("review",source,"Verify behavior across branches and compare configurable transform",
          [[6,6,"blue"],[10,0,"blue"]],[process(source),process(source,factor=5,offset=-2)])
    failures = []
    for row in ({"mode":"scale"},{"mode":"unknown","score":2}):
        try:
            process([row])
        except KeyError as error:
            failures.append(error.args[0])
    check("invalid_rows",["missing score","unknown mode"],"Call two omitted-contract branches and catch the precise key",
          ["score","unknown"],failures)
    capture = io.StringIO()
    logger = logging.Logger("mbsky.exercise",level=logging.DEBUG)
    logger.addHandler(logging.StreamHandler(capture))
    a,b = 9,4
    result = a + b*(a-b)
    logger.debug("difference=%d result=%d",a-b,result)
    check("logging",[a,b],"Capture the actual operations and result with debug logging",
          [29,"difference=5 result=29"],[result,capture.getvalue().strip()])
    with socket.socket() as reservation:
        reservation.bind(("127.0.0.1",0))
        host,port = reservation.getsockname()
        failure = None
        try:
            socket.create_connection((host,port),timeout=1).close()
        except OSError as error:
            failure = type(error).__name__
        check("network","Loopback TCP port bound without listen","Perform a local connection attempt",
              True,failure in ("ConnectionRefusedError","TimeoutError"))
        cases[-1]["observed_error"] = failure
    with TemporaryDirectory(prefix="mbsky-codex-cli-examples-") as temporary:
        root=Path(temporary)
        home=root/"profile"
        repo=root/"repo"
        home.mkdir()
        repo.mkdir()
        env={k:v for k,v in os.environ.items() if not k.startswith(("CODEX_","GIT_"))}
        env.update(CODEX_HOME=str(home),GIT_CONFIG_NOSYSTEM="1",GIT_CONFIG_GLOBAL=os.devnull)

        def git_run(*args):
            return subprocess.run([git,"-c","core.autocrlf=false","-c","commit.gpgsign=false",*args],
                                  cwd=repo,env=env,capture_output=True,encoding="utf8",check=True,timeout=15).stdout.strip()

        for filename in ("image_007.jpg","image_103.jpg","manual.txt"):
            (repo/filename).write_bytes(filename.encode())
        plan = [(x,x.with_name(x.name.replace("_","-",1))) for x in sorted(repo.glob("image_???.jpg"))]
        assert all(not target.exists() for _,target in plan)
        for start,target in plan:
            start.rename(target)
        check("rename",["image_007.jpg","image_103.jpg","manual.txt"],"Check destination collisions and rename only matching fixture files",
              ["image-007.jpg","image-103.jpg","manual.txt"],sorted(p.name for p in repo.iterdir()))
        paths = {"app.py":"from auth import current_user\n","config.py":"DEBUG = False\n",
                 "requirements.txt":"Flask\n","auth.py":"def current_user():\n    return 'guest'\n",
                 "tests/test_fixture.py":"import unittest\n\nclass LayoutTest(unittest.TestCase):\n    def test_total(self):\n        self.assertEqual(sum([1,2,3]),6)\n",
                 "static/.keep":"","templates/.keep":""}
        for name,content in paths.items():
            file=repo/name
            file.parent.mkdir(exist_ok=True)
            file.write_bytes(content.encode())
        check("layout",list(paths),"Create the staged skeleton; static analysis resolves Python import statements",
              ["app.py"],[file.name for file in repo.glob("*.py") if "from auth import " in file.read_text(encoding="utf8")])
        test=subprocess.run([sys.executable,"-B","-m","unittest","discover","-s","tests"],cwd=repo,env=env,capture_output=True,encoding="utf8",timeout=15)
        check("tests",["unittest","discover","-s","tests"],"Run the repository's own unit test",
              [0,True,True],[test.returncode,"Ran 1 test" in test.stderr,test.stderr.strip().endswith("OK")])
        git_run("init","--quiet","--template=","--initial-branch=main")
        git_run("add","--","app.py","auth.py","tests/test_fixture.py")
        staged=git_run("diff","--cached","--name-only").splitlines()
        git_run("-c","user.name=Exercise Author","-c","user.email=exercise@example.invalid",
                "commit","--quiet","-m","Add isolated example")
        check("commit",staged,"Check staged paths, create fixture commit, and compare saved paths with actual Git output",
              ["app.py","auth.py","tests/test_fixture.py"],git_run("show","--pretty=format:","--name-only","HEAD").splitlines())
        version=subprocess.run([codex,"--version"],cwd=repo,env=env,capture_output=True,encoding="utf8",check=True,timeout=15).stdout.strip()
        print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version,"git":git_run("--version")},
                              codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),cases=cases)))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 并列时取最早索引,生成器耗尽后为空,环回端口拒绝连接或超时,临时仓库仅提交指定文件。
运行函数、复现连接失败并核对临时仓库操作

所需环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。

当前源码 SHA256:47617465dfdd5a56912757245c1330abf47f08cec6cc3a47e8bd3f50cbc48b56

CLI 实例 ZIP

含 Python 自编练习、测试仓库步骤和本地结果页。

下载 CLI 可重现实例

所需环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。

ZIP SHA256:d71a3a53b9bb6e083ab3fce1709bf51b8782b91420e37f06ca93966d7ee17649

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为最长字符串函数增加两个等长 Unicode 输入,问清长度定义再补断言。

展开参考解答

按当前 Python len 的定义两项同长时返回最早索引。

规范与官方依据