跳至主要內容
模組 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年10月21日

你將學到什麼

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

本文已依 Claude Code 2.1.305 的 command contract 驗證。重要自動化前,先執行 claude --version 並重新核對最新 CLI reference。claude --help 不會列出所有 文件化的 flags,例如 --max-turns 只出現在 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 --verbose --include-partial-messages \
  "Report progress while reviewing this repository."

JSON 結果的 result 欄位放回應文字,另含 session_id 等 metadata。文件中的 串流寫法會把 stream-json 與 --verbose 搭配使用;--include-partial-messages 則會加入 token 層級的 events。

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

使用 JSON Schema

--json-schema 會依 schema 驗證 print-mode 輸出。請搭配 --output-format json:驗證後的物件會出現在 structured_output 欄位。 請引用整段 schema,避免 shell 切割或展開。

claude -p --output-format json \
  --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." \
  | jq '.structured_output'

若執行結束時沒有有效的結構化輸出(例如 Claude 拒絕了請求),回應中就不會 有 structured_output 欄位;使用前請先確認欄位存在。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 審查。

若 flag 與 permissions.defaultMode 都沒有指定模式,v2.1.302 以後的 claude -p 會以 Manual 模式(設定值 default)啟動。需要核准的呼叫一律 拒絕,除非有 allow rule(例如 --allowedTools "Bash(npm test *)")、hook 或 --permission-prompt-tool 核准。請只授予任務需要的最小範圍,或刻意選擇 auto、dontAsk 等模式。

若執行時有 permission host(例如 Agent SDK 的 canUseTool callback 或 --permission-prompt-tool),卻沒有人會回應,請加上 --permission-prompts none(v2.1.259 以後),讓這些提示直接被拒絕,而不是 一直等待。

明確地繼續 Session

重現性重要時,以明確 session ID 恢復。可從 JSON 輸出取得 ID:

session_id=$(claude -p --output-format json "Start the review." | jq -r '.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,並確認 structured_output 存在。
  • 限制 turns,並明確選擇 permission mode,不要依賴預設值。
  • 只在信任的 repository 執行 -p:它會略過 workspace trust 對話框,仍會執行 project hooks 與 .mcp.json servers。面對非自己撰寫的程式碼,請以 --bare 啟動;此時在 Anthropic API 上只會使用 ANTHROPIC_API_KEY 或透過 --settings 傳入的 apiKeyHelper 驗證。
  • 恢復 session 後重新驗證 worktree。
  • 絕不把模型輸出直接插入 shell。

下一步

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