"""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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。
入口文件:projects/codex-cli_examples/cli_examples_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cli_examples_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、git version 2.54.0.windows.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a95.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip