跳至主要內容
模組 3:真實架構 1 / 6
進階 S13 Claude Code CLI Print Mode Structured Output Automation

CLI 控制介面:Print Mode、JSON 與 Sessions

使用 print mode、結構化輸出、turn 上限、權限模式與可恢復 session,把 Claude Code 當成有邊界的 CLI process。

2026年3月20日 12 分鐘閱讀
已校驗 課程最近校驗: 2026年7月31日
Claude Code ≥ 2.1.226 官方來源 1

你將學到什麼

Claude Code 不只是一個互動式 TUI。正式發布的 CLI 能執行單次、有邊界的 任務,輸出 machine-readable 資料、套用 JSON Schema、限制 agent turns、 指定 permission mode,並恢復已保存的 session。

本文依據 Claude Code 2.1.226。重要自動化前,先執行 claude --version 並重新核對最新 CLI reference。

從 Print Mode 開始

-p--print 的縮寫:Claude 以非互動模式執行,輸出結果後結束。

claude -p "Summarize the changed files and report which tests ran."

不要把其他 CLI 的 -p 語意搬過來。Codex 的 -p 選擇 configuration profile;Grok Build 的 -p 則是 single-turn prompt。

選擇輸出契約

人類閱讀用 text;單一結構化結果用 JSON;需要 incremental events 時用 stream JSON。

claude -p --output-format text "Explain the failing test."
claude -p --output-format json "Return the repository status."
claude -p --output-format stream-json --include-partial-messages \
  "Report progress while reviewing this repository."

輸出仍是不受信任的資料。解析並驗證結構,且不要直接把內容拼進 shell command。

使用 JSON Schema

--json-schema 可約束 print-mode 輸出。請引用整段 schema,避免 shell 切割或展開。

claude -p \
  --json-schema '{"type":"object","properties":{"summary":{"type":"string"},"tests":{"type":"array","items":{"type":"string"}}},"required":["summary","tests"],"additionalProperties":false}' \
  "Review the current diff and return the requested fields."

Schema 只能驗證形狀,不能保證內容為真;呼叫端仍需檢查檔案、測試與外部 狀態。

限制權限與工作量

Turn 上限與 permission mode 是兩個不同控制面:

claude -p \
  --max-turns 6 \
  --permission-mode plan \
  "Map the implementation path and risks without editing."

--max-turns 限制 agent loop;--permission-mode 決定 tool authority。 兩者都不能取代 OS sandbox、repository isolation 或 destructive command 審查。

明確地繼續 Session

重現性重要時,以明確 session ID 恢復:

claude -p --resume SESSION_ID \
  "Continue from the saved context and re-check the current worktree first."

--continue 會選擇目前 directory 最近的 conversation,較方便但不夠明確:

claude -p --continue "Continue only if the repository state still matches."

保存的 context 可能過期。每次恢復後都要重新檢查 instructions、permissions、 branch、diff 與 tests。

Production Checklist

  • 固定並記錄 Claude Code 版本。
  • 只把 -p 解讀為 Claude print mode。
  • 選定 output format,並驗證 machine-readable output。
  • 下游依賴欄位時加入 JSON Schema。
  • 限制 turns,並選擇明確 permission mode。
  • 恢復 session 後重新驗證 worktree。
  • 絕不把模型輸出直接插入 shell。

下一步

Session 14 會把這個有邊界的 CLI workflow 連接到 MCP server,並維持明確 的 server trust 與 tool authority。