跳转到内容

非交互模式

身份 非官方简体中文镜像
翻译状态 AI 翻译
来源版本 官方未提供
同步日期 2026-07-31
官方原文 learn.chatgpt.com

如需完整文档索引,请参阅 llms.txt。文档页面的 Markdown 版本可通过在页面后追加 .md 来获取 URL。

非交互模式允许你从脚本中运行 Codex(例如持续集成 (CI) 作业),而无需打开交互式 TUI。 使用 codex exec 调用它。

有关标志级别的详细信息,请参阅 codex exec

使用 codex exec 当你想要 Codex :

  • 作为流水线的一部分运行(CI、合并前检查、计划任务)。
  • 生成可通过管道传递给其他工具的输出(例如生成发布说明或摘要)。
  • 自然融入 CLI 工作流,将命令输出传递给 Codex,并将 Codex 输出传递给其他工具。
  • 使用显式预设的沙箱和批准设置运行。

将任务提示作为单个参数传入:

Terminal window
codex exec "summarize the repository structure and list the top 5 risky areas"

运行 codex exec 时,Codex 会将进度流式输出到 stderr,并仅将最终 Agent 消息输出到 stdout。这样可以轻松地重定向或通过管道传递最终结果:

Terminal window
codex exec "generate release notes for the last 10 commits" | tee release-notes.md

如果不希望将会话 rollout 文件持久化到磁盘,请使用 --ephemeral

Terminal window
codex exec --ephemeral "triage this repository and suggest next steps"

如果通过管道传入 stdin,同时又提供了提示参数,Codex 会将该提示视为指令,并将管道内容视为附加上下文。

这样可以轻松地使用一个命令生成输入,并将其直接交给 Codex:

Terminal window
curl -s https://jsonplaceholder.typicode.com/comments \
| codex exec "format the top 20 items into a markdown table" \
> table.md

有关更高级的 stdin 管道模式,请参阅高级 stdin 管道

默认情况下,codex exec 在只读沙箱中运行。在自动化环境中,请根据工作流设置所需的最小权限:

  • 允许编辑:codex exec --sandbox workspace-write "<task>"
  • 允许更广泛的访问:codex exec --sandbox danger-full-access "<task>"

仅在受控环境中使用 danger-full-access(例如隔离的 CI runner 或容器)。

Codex 保留 codex exec --full-auto 作为已弃用的兼容性标志,并会打印警告。对于新脚本,建议使用显式的 --sandbox workspace-write 标志。

使用 --ignore-user-config 当你需要一次不加载 $CODEX_HOME/config.toml的运行,并且 --ignore-rules 当你需要跳过用户和项目 execpolicy .rules 文件以用于受控自动化环境时。

如果你配置了一个启用的 MCP server,并将 required = true,而该服务器初始化失败,codex exec 会退出并报错,而不是在没有该服务器的情况下继续运行。

要在脚本中使用 Codex 输出,请使用 JSON Lines 输出:

Terminal window
codex exec --json "summarize the repo structure" | jq

启用 --json 后,stdout 会变为 JSON Lines (JSONL) 流,因此你可以捕获 Codex 运行期间发出的每个事件。事件类型包括 thread.startedturn.startedturn.completedturn.faileditem.*error

项目类型包括 Agent 消息、推理、命令执行、文件更改、MCP 工具调用、网页搜索和计划更新。

JSON 流示例(每行都是一个 JSON 对象):

{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Repo contains docs, sdk, and examples directories."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122,"reasoning_output_tokens":0}}

如果只需要最终消息,请使用 -o <path>/--output-last-message <path> 将其写入文件。这会将最终消息写入文件,同时仍将其打印到 stdout(详情请参阅 codex exec)。

如果下游步骤需要结构化数据,请使用 --output-schema,要求最终响应符合 JSON Schema。 这对于需要稳定字段的自动化工作流很有用(例如作业摘要、风险报告或发布元数据)。

schema.json

{
"type": "object",
"properties": {
"project_name": { "type": "string" },
"programming_languages": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["project_name", "programming_languages"],
"additionalProperties": false
}

使用该架构运行 Codex,并将最终 JSON 响应写入磁盘:

Terminal window
codex exec "Extract project metadata" \
--output-schema ./schema.json \
-o ./project-metadata.json

最终输出示例(stdout):

{
"project_name": "Codex CLI",
"programming_languages": ["Rust", "TypeScript", "Shell"]
}

默认情况下,codex exec 会重用已保存的 CLI 身份验证信息。在 CI 中,通常需要显式提供凭据:

对于 GitHub Actions,请使用 Codex GitHub Action ,而不是自行安装和认证 CLI 。该 action 旨在通过安装 API 来减少密钥暴露 Codex、启动 Responses API 代理,并运行 Codex ,同时使用可配置的安全策略。

对于会检出或运行由仓库控制的代码的工作流,请勿将 OPENAI_API_KEYCODEX_API_KEY 设置为作业级环境变量。同一作业中的构建脚本、测试、依赖项生命周期钩子或受入侵的 action 都可能读取这些环境变量。

对于其他自动化环境,请设置 CODEX_API_KEY 仅用于单次 codex exec 调用,并确保没有不受信任的代码在同一进程环境中运行。

若要为单次运行使用其他 API 密钥,请以内联方式设置 CODEX_API_KEY

Terminal window
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"

CODEX_API_KEY 仅支持在 codex exec 中使用。

如果你需要运行 CI/CD 作业,并使用 Codex 用户账户而不是 API 密钥,请阅读本文,例如使用 ChatGPT托管 Codex 访问权限的企业团队,在受信任的 运行器上运行,或需要 ChatGPT/Codex 速率限制而不是 API 密钥用量的用户。

API 密钥是自动化的正确默认选择,因为它们更容易 预配和轮换。仅当你明确需要以 你的 Codex 账户运行时,才使用此路径。

~/.codex/auth.json 像密码一样对待:它包含访问令牌。不要 提交它、将其粘贴到工单中,或在聊天中分享。

不要将此工作流用于公共或开源仓库。如果 codex login 在运行器上不可用,请通过安全存储预置 auth.json ,在运行器上运行 Codex ,以便 Codex 在原处刷新它,并在运行之间保留更新后的文件 。

请参阅 维护 Codex 账户认证于 CI/CD (高级)

如果需要继续之前的运行(例如两阶段流水线),请使用 resume 子命令:

Terminal window
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"

你也可以定位特定会话 ID 使用 codex exec resume <SESSION_ID>

Codex 要求命令在 Git 仓库内运行,以防止破坏性更改。如果确定环境安全,可以使用 codex exec --skip-git-repo-check 覆盖此检查。

示例:自动修复 CI 中的失败 GitHub Actions

Section titled “示例:自动修复 CI 中的失败 GitHub Actions”

对于 GitHub Actions 工作流,请使用 openai/codex-action,而不是安装 Codex 并将 API 密钥传递给 shell 步骤。该 action 会为 OpenAI API 密钥启动安全代理。

你可以使用 Codex 在 CI 工作流失败时自动提出修复方案。模式如下:

  1. 在主 CI 工作流完成且出错后,触发后续工作流。
  2. 仅使用仓库读取权限检出失败的提交。
  3. 在 Codex 运行前执行设置命令,并且不要将 OpenAI API 密钥暴露给这些步骤。
  4. 运行 Codex GitHub Action。
  5. 将 Codex 的本地更改保存为补丁构件。
  6. 在单独的作业中应用补丁并创建拉取请求。

下面的 Codex 作业只有 contents: read 权限。Codex 运行后,它只会将差异序列化为构件。open_pr 作业会获得仓库写入权限,但不会获得 OPENAI_API_KEY

该示例假设使用 Node.js 项目。请根据你的技术栈调整设置和测试命令。

有关更深入的安全检查清单,请参阅 Codex GitHub Action 安全指南

name: Codex auto-fix on CI failure
on:
workflow_run:
workflows: ["CI"]
types: [completed]
jobs:
generate_fix:
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
has_patch: ${{ steps.diff.outputs.has_patch }}
steps:
- uses: actions/checkout@v5
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: |
if [ -f package-lock.json ]; then npm ci; fi
- name: Run Codex
uses: openai/codex-action@v1
with:
openai-api-key: ${{ secrets.OPENAI_API_KEY }}
prompt: |
The CI workflow "${{ github.event.workflow_run.name }}" failed for commit
${{ github.event.workflow_run.head_sha }}.
Run `npm test --silent` to reproduce the failure. Identify the minimal
change needed to make the tests pass, implement only that change, and
run `npm test --silent` again.
Do not refactor unrelated files.
- name: Create patch artifact
id: diff
run: |
git add -N .
git diff --binary HEAD > codex.patch
if [ -s codex.patch ]; then
echo "has_patch=true" >> "$GITHUB_OUTPUT"
else
echo "has_patch=false" >> "$GITHUB_OUTPUT"
fi
- name: Upload patch artifact
if: steps.diff.outputs.has_patch == 'true'
uses: actions/upload-artifact@v4
with:
name: codex-fix-patch
path: codex.patch
if-no-files-found: error
open_pr:
runs-on: ubuntu-latest
needs: generate_fix
if: needs.generate_fix.outputs.has_patch == 'true'
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v5
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
- uses: actions/download-artifact@v4
with:
name: codex-fix-patch
- name: Apply Codex patch
run: git apply --index codex.patch
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
FAILED_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
FAILED_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
RUN_ID: ${{ github.event.workflow_run.run_id }}
run: |
branch="codex/auto-fix-$RUN_ID"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "$branch"
git commit -m "Auto-fix failing CI via Codex"
git push origin "$branch"
{
echo "Codex generated this patch after CI failed for \`$FAILED_HEAD_SHA\`."
echo
echo "Review the changes before merging."
} > pr-body.md
gh pr create \
--base "$FAILED_HEAD_BRANCH" \
--head "$branch" \
--title "Auto-fix failing CI via Codex" \
--body-file pr-body.md

当另一个命令为 Codex 生成输入时,请根据指令的来源选择 stdin 模式。如果你已经知道指令,并希望将管道输出作为上下文传入,请使用“提示加 stdin”。如果 stdin 应作为完整提示,请使用 codex exec -

当另一个命令已经生成了你希望 Codex 检查的数据时,提示加 stdin 模式非常有用。在此模式下,你编写指令,并将输出通过管道作为上下文传入,非常适合围绕命令输出、日志和生成数据构建的 CLI 工作流。

Terminal window
npm test 2>&1 \
| codex exec "summarize the failing tests and propose the smallest likely fix" \
| tee test-summary.md

Terminal window
tail -n 200 app.log \
| codex exec "identify the likely root cause, cite the most important errors, and suggest the next three debugging steps" \
> log-triage.md

Terminal window
curl -vv https://api.example.com/health 2>&1 \
| codex exec "explain the TLS or HTTP failure and suggest the most likely fix" \
> tls-debug.md

Terminal window
gh run view 123456 --log \
| codex exec "write a concise Slack-ready update on the CI failure, including the likely cause and next step" \
| pbcopy

Terminal window
gh run view 123456 --log \
| codex exec "summarize the failure in 5 bullets for the pull request thread" \
| gh pr comment 789 --body-file -

如果省略提示参数,Codex 会从 stdin 读取提示。当你希望显式强制执行此行为时,请使用 codex exec -

当另一个命令或脚本动态生成完整提示时,- 占位符非常有用。当你将提示存储在文件中、使用 shell 脚本组装提示,或在将完整提示交给 Codex 前将实时命令输出与指令组合起来时,这种方式非常适合。

Terminal window
cat prompt.txt | codex exec -
Terminal window
printf "Summarize this error log in 3 bullets:\n\n%s\n" "$(tail -n 200 app.log)" \
| codex exec -
Terminal window
generate_prompt.sh | codex exec - --json > result.jsonl