Codex 非交互执行:标准输入、事件和流水线产物
按当前 CLI 核对参数与权限,并用本地进程验证失败时保留既有产物。
学完这一章,你能够
- 按当前 CLI 核对参数与权限,并用本地进程验证失败时保留既有产物。
把任务作为参数或标准输入交给程序
codex exec 接受引号保护的任务文本。需要从管道、文件或多行脚本输入完整任务时,使用单独的位置参数 -。若同时提供任务参数与管道输入,当前版本可把管道内容用作额外上下文,按实际任务确定时机和数据范围。
本机帮助接受位置参数 -,并拒绝旧 --stdin。-m 可选择账户或提供方实际可用的模型。标准输出可取得最终消息,-o 或 --output-last-message 写入文件。用 --json 接收逐行事件,需要时用 --output-schema 约束最后消息的结构。
为非交互任务写清权限与时限
默认只读行为应与实际生效配置核对。需要编辑时明确允许范围和验证命令。旧 --no-auto-approve 和 --approval 不能作为本机策略。当前选项以 CLI 参考为准,可在受控非交互任务中选择适用沙箱及审批,不能承诺任务中能取得交互确认。
旧例的 [exec].default_model、auto_approve_threshold 和 timeout 属于历史写法,现行型号可由 model 或 -m 指定,审批由现行配置决定,任务截止时间可由 CI 作业或本地子进程控制。批量任务按文件或模块定义独立验收。引用文件路径时保留引号和空格,规范化生成文件名并防止同名覆盖。
验证可用的最终结果才替换产物
把进程退出码、标准错误与逐行事件分开检查。读取事件时确认任务已完成、最终消息存在且格式可用,再把产物写到临时路径并替换目标。退出成功也可能没有有效消息。
本站真实运行独立子进程,分别观测成功写入、失败保护、无效 JSON 与缺完成事件。后面三种保留原产物。图中显示网页结果,事件来自本站样例,本机无需向模型发出请求。

按文件数决定是否批处理时明确阈值、文件集合、单次工作大小和失败恢复。先用固定输入确认输出,再逐步扩大范围。使用实际总耗时和价格判断成本,历史 gpt-5.4-mini 已不适用于所有认证渠道。
在 CI 或容器里复用同一验收
GitHub Actions 可用 Codex Action 直接执行任务。选择授权的 PR 事件和范围,传入受保护的秘密。把输出保存为产物供复核。Action 负责安装和运行,具体输入以版本为准。
GitLab CI 可在固定版本镜像内安装 CLI 并通过受保护变量认证,再运行 exec 和登记 artifact。Jenkins 可在适用代理节点运行 Shell 并在 post 阶段收集明确命名的产物。处理失败时区分旧产物与本次部分结果。
在 Docker 里建立确定的工作目录、依赖与授权,避免把凭据写进镜像。对真实 CI 按环境检查访问权限、时限和失败回滚。本章只验证本机样例和 CLI 参数解析,远程流水线待执行。
常用入口迁移
| 参数 | 现行含义或迁移 |
|---|---|
| exec "任务" | 将任务文本作为一个位置参数交给非交互入口。 |
| --stdin | 本机不接受该旧旗标。用位置参数 - 从标准输入读任务。 |
| --model, -m | 覆盖本次的模型。按客户端与账户核对可用性。 |
| --no-auto-approve | 本机不接受此历史旗标,改查当前审批与沙箱。 |
| --output, -o | 本机拒绝 --output;-o 或 --output-last-message 保存最终消息。 |
核对旧参数并验证脚本产物替换
"""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()
- 本机拒绝四个旧选项。自编子进程成功时写报告,退出失败、JSON 损坏或少完成事件时保存原结果。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
当前源码 SHA256:203cd1f764aead8a8f28759e49f3b51e9ab793cd5047701a0cf9bd3b4d497dea
非交互产物练习 ZIP
含参数检查、运行说明、本地子进程脚本及观测页。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
ZIP SHA256:4eba7852df5bce440ab9b75fda0f35e4e021ea5914691ab66b96e56a61c98844
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
改变样例事件使其缺少最终消息,保留完成标记。
展开参考解答
代码应返回 missing_message 并保留上次产物。