蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

核对旧参数并验证脚本产物替换

PYTHONWindows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。noninteractive_lab.py
noninteractive_lab.py102 行
"""Test installed exec option parsing and a local subprocess artifact workflow."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory


TASK = """Inspect the local catalog.
Report the number of entries.
"""
CHILD = """
import json
import sys
text = sys.stdin.read()
if not text.strip():
    print("empty input", file=sys.stderr)
    raise SystemExit(3)
print(json.dumps({"type":"item.completed","item":{"type":"agent_message","text":text}}))
print(json.dumps({"type":"turn.completed"}))
"""


def publish(result, target):
    if result.returncode:
        return "child_failed"
    try:
        events = [json.loads(line) for line in result.stdout.splitlines()]
    except json.JSONDecodeError:
        return "invalid_json"
    if not events or events[-1]["type"] != "turn.completed":
        return "missing_completion"
    answers = [row["item"]["text"] for row in events if row["type"]=="item.completed"
               and row["item"]["type"]=="agent_message"]
    if not answers:
        return "missing_message"
    staged = target.with_suffix(".pending")
    staged.write_bytes(answers[-1].encode())
    staged.replace(target)
    return "saved"


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

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

    with TemporaryDirectory(prefix="mbsky-exec-fixture-") as temporary:
        root=Path(temporary)
        env=dict(os.environ,CODEX_HOME=temporary)

        def invoke(*args):
            return subprocess.run([codex,*args],cwd=root,env=env,capture_output=True,encoding="utf8",timeout=10)

        for name,args in (("stdin",["--stdin"]),("auto",["--no-auto-approve"]),
                          ("output",["--output","review.md"]),("approval",["--approval","deny"])):
            result=invoke("exec",*args,"--help")
            check("old_"+name,args,"Read the installed exec parser's response to a legacy flag",
                  [2,True],[result.returncode,"unexpected argument" in result.stderr])

        args=["exec","-","--help"]
        result=invoke(*args)
        check("new_help",args,"Verify parser accepts the positional stdin marker and lists current output flags",
              [0,True,True],[result.returncode,"--output-last-message" in result.stdout,"--json" in result.stdout])
        version=invoke("--version")
        assert version.returncode == 0

        def local_child(text, script=CHILD):
            return subprocess.run([sys.executable,"-I","-B","-X","utf8","-c",script],
                                  cwd=root,input=text,capture_output=True,encoding="utf8",timeout=8)

        target=root/"review.md"
        result=local_child(TASK)
        check("success",{"stdin":TASK,"source":CHILD},"Run the local fixture and publish on a successful JSONL completion",
              [0,"saved",TASK],[result.returncode,publish(result,target),target.read_bytes().decode()])
        result=local_child("")
        check("failure",{"stdin":"","source":CHILD},"Reject a failed child and retain the verified artifact",
              [3,"child_failed",TASK],[result.returncode,publish(result,target),target.read_bytes().decode()])
        result=local_child(TASK,'print("{broken")')
        check("malformed","send malformed stdout using a successful local child",
              "Reject invalid JSONL and retain the prior artifact",
              [0,"invalid_json",TASK],[result.returncode,publish(result,target),target.read_bytes().decode()])
        result=local_child(TASK, 'import json; print(json.dumps({"type":"turn.started"}))')
        check("incomplete","only a started event","Reject an incomplete stream and retain the earlier artifact",
              [0,"missing_completion",TASK],[result.returncode,publish(result,target),target.read_bytes().decode()])

    print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version.stdout.strip()},
                          codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),cases=cases)))


if __name__=="__main__":
    main()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。

入口文件:projects/codex-noninteractive/noninteractive_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 noninteractive_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a114.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习