非交互模式
使用 Codex 在非交互模式下自動化常見工作流程。
codex exec "count the total number of lines of code in this project"在非交互模式下,Codex 不要求命令或編輯批准。預設情況下,它以 read-only 模式運行,因此無法編輯文件或運行需要網絡訪問的命令。
使用 codex exec --full-auto 允許文件編輯。使用 codex exec --sandbox danger-full-access 允許編輯和網絡命令。
預設輸出模式
預設情況下,Codex 將其活動流傳輸到 stderr,並僅將代理的最後消息寫入 stdout。這使將 codex exec 管道傳輸到另一個工具而無需額外過濾變得更容易。
要將 codex exec 的輸出寫入文件,除了使用 shell 重定向(如 >)外,還有一個專用標誌來指定輸出文件:-o/--output-last-message。
JSON 輸出模式
codex exec 支持 --json 模式,在代理運行時將事件作為 JSON Lines (JSONL) 流式傳輸到 stdout。
支持的事件類型:
thread.started- 當線程啟動或恢復時。turn.started- 當轉輪開始時。轉輪包含用戶消息和助手響應之間的所有事件。turn.completed- 轉輪完成時;包括令牌使用情況。turn.failed- 當轉輪失敗時;包括錯誤詳情。item.started/item.updated/item.completed- 當添加/更新/完成線程項時。error- 當流報告無法恢復的錯誤時;包括錯誤消息。
支持的項類型:
agent_message- 助手消息。reasoning- 助手思考的摘要。command_execution- 助手執行命令。file_change- 助手進行文件更改。mcp_tool_call- 助手調用 MCP 工具。web_search- 助手執行 web 搜索。todo_list- 計劃工具活躍時的代理運行計劃,在步驟更改時更新。
通常,agent_message 在轉輪結束時被添加。
示例輸出:
{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"**Searching for README files**"}}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","aggregated_output":"","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","aggregated_output":"2025-09-11\nAGENTS.md\nCHANGELOG.md\ncliff.toml\ncodex-cli\ncodex-rs\ndocs\nexamples\nflake.lock\nflake.nix\nLICENSE\nnode_modules\nNOTICE\npackage.json\npnpm-lock.yaml\npnpm-workspace.yaml\nPNPM.md\nREADME.md\nscripts\nsdk\ntmp\n","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_2","type":"reasoning","text":"**Checking repository root for README**"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Yep — there's a `README.md` in the repository root."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122}}結構化輸出
預設情況下,代理使用自然語言響應。使用 --output-schema 提供定義預期 JSON 輸出的 JSON Schema。
JSON Schema 必須遵循嚴格模式規則。
示例 schema:
{
"type": "object",
"properties": {
"project_name": { "type": "string" },
"programming_languages": { "type": "array", "items": { "type": "string" } }
},
"required": ["project_name", "programming_languages"],
"additionalProperties": false
}codex exec "Extract details of the project" --output-schema ~/schema.json
...
{"project_name":"Codex CLI","programming_languages":["Rust","TypeScript","Shell"]}將 --output-schema 與 -o 結合以僅打印最終 JSON 輸出。您也可以將文件路徑傳遞到 -o 以將 JSON 輸出保存到文件。
Git 存儲庫要求
Codex 需要 Git 存儲庫以避免破壞性更改。要禁用此檢查,請使用 codex exec --skip-git-repo-check。
恢復非交互式會話
使用 codex exec resume <SESSION_ID> 或 codex exec resume --last 恢復以前的非交互式會話。這保留了會話上下文,以便您可以提出後續問題或給代理新的任務。
codex exec "Review the change, look for use-after-free issues"
codex exec resume --last "Fix use-after-free issues"只有對話上下文被保留;您仍然必須提供標誌來自定義 Codex 行為。