ヘッドレスモード
ヘッドレスモードを使用すると、インタラクティブな UI なしで、コマンドラインスクリプトや自動化ツールからプログラム的に Qwen Code を実行できます。スクリプティング、自動化、CI/CD パイプライン、AI 駆動ツールの構築に最適です。
概要
ヘッドレスモードは、以下の機能を持つ Qwen Code のヘッドレスインターフェースを提供します:
- コマンドライン引数または stdin 経由でプロンプトを受け付ける
- 構造化された出力(テキストまたは JSON)を返す
- ファイルのリダイレクトとパイプ処理をサポートする
- 自動化およびスクリプティングワークフローを可能にする
- エラー処理のために一貫した終了コードを提供する
- 複数ステップの自動化のために、現在のプロジェクトにスコープされた以前のセッションを再開できる
基本的な使い方
直接プロンプト
ヘッドレスモードで実行するには、--prompt(または -p)フラグを使用します:
qwen --prompt "What is machine learning?"Stdin 入力
ターミナルから Qwen Code に入力をパイプします:
echo "Explain this code" | qwenファイル入力との組み合わせ
ファイルから読み取り、Qwen Code で処理します:
cat README.md | qwen --prompt "Summarize this documentation"以前のセッションの再開(ヘッドレス)
ヘッドレススクリプトで、現在のプロジェクトの会話コンテキストを再利用します:
# Continue the most recent session for this project and run a new prompt
qwen --continue -p "Run the tests again and summarize failures"
# Resume a specific session ID directly (no UI)
qwen --resume 123e4567-e89b-12d3-a456-426614174000 -p "Apply the follow-up refactor"- セッションデータは、
~/.qwen/projects/<sanitized-cwd>/chats配下のプロジェクトスコープの JSONL として保存されます。 - 新しいプロンプトを送信する前に、会話履歴、ツール出力、チャット圧縮チェックポイントを復元します。
メインセッションプロンプトのカスタマイズ
共有メモリファイルを編集することなく、単一の CLI 実行に対してメインセッションのシステムプロンプトを変更できます。
組み込みシステムプロンプトの上書き
--system-prompt を使用して、現在の実行における Qwen Code の組み込みメインセッションプロンプトを置き換えます:
qwen -p "Review this patch" --system-prompt "You are a terse release reviewer. Report only blocking issues."追加指示の付加
--append-system-prompt を使用して、組み込みプロンプトを維持したまま、この実行用の追加指示を付加します:
qwen -p "Review this patch" --append-system-prompt "Be terse and focus on concrete findings."カスタムベースプロンプトと実行固有の追加指示の両方を使用したい場合は、両方のフラグを組み合わせることができます:
qwen -p "Summarize this repository" \
--system-prompt "You are a migration planner." \
--append-system-prompt "Return exactly three bullets."--system-promptは、現在の実行のメインセッションにのみ適用されます。QWEN.mdなどの読み込まれたメモリおよびコンテキストファイルは、--system-promptの後に引き続き追加されます。--append-system-promptは組み込みプロンプトおよび読み込まれたメモリの後に適用され、--system-promptと組み合わせて使用できます。
出力フォーマット
Qwen Code は、さまざまなユースケースに対応する複数の出力フォーマットをサポートしています:
テキスト出力(デフォルト)
標準の人間が読める形式の出力:
qwen -p "What is the capital of France?"レスポンスフォーマット:
The capital of France is Paris.JSON 出力
構造化データを JSON 配列として返します。すべてのメッセージはバッファリングされ、セッション完了時にまとめて出力されます。このフォーマットは、プログラムによる処理や自動化スクリプトに最適です。
JSON 出力はメッセージオブジェクトの配列です。出力には複数のメッセージタイプが含まれます:システムメッセージ(セッション初期化)、アシスタントメッセージ(AI レスポンス)、結果メッセージ(実行サマリー)。
使用例
qwen -p "What is the capital of France?" --output-format json出力(実行終了時):
[
{
"type": "system",
"subtype": "session_start",
"uuid": "...",
"session_id": "...",
"model": "qwen3-coder-plus",
...
},
{
"type": "assistant",
"uuid": "...",
"session_id": "...",
"message": {
"id": "...",
"type": "message",
"role": "assistant",
"model": "qwen3-coder-plus",
"content": [
{
"type": "text",
"text": "The capital of France is Paris."
}
],
"usage": {...}
},
"parent_tool_use_id": null
},
{
"type": "result",
"subtype": "success",
"uuid": "...",
"session_id": "...",
"is_error": false,
"duration_ms": 1234,
"result": "The capital of France is Paris.",
"usage": {...}
}
]Stream-JSON 出力
Stream-JSON フォーマットは、実行中に発生した JSON メッセージを即座に出力し、リアルタイムモニタリングを可能にします。このフォーマットは、各行が完全な JSON オブジェクトである行区切り JSON を使用します。
qwen -p "Explain TypeScript" --output-format stream-json出力(イベント発生時のストリーミング):
{"type":"system","subtype":"session_start","uuid":"...","session_id":"..."}
{"type":"assistant","uuid":"...","session_id":"...","message":{...}}
{"type":"result","subtype":"success","uuid":"...","session_id":"..."}--include-partial-messages と組み合わせると、リアルタイム UI 更新のために追加のストリームイベント(message_start、content_block_delta など)がリアルタイムで出力されます。
qwen -p "Write a Python script" --output-format stream-json --include-partial-messages入力フォーマット
--input-format パラメータは、Qwen Code が標準入力から入力をどのように消費するかを制御します:
text(デフォルト):stdin またはコマンドライン引数からの標準テキスト入力stream-json:双方向通信のための stdin 経由の JSON メッセージプロトコル
注記: Stream-json 入力モードは現在構築中であり、SDK 統合を目的としています。
--output-format stream-jsonの設定が必要です。
ファイルリダイレクト
出力をファイルに保存するか、他のコマンドにパイプします:
# Save to file
qwen -p "Explain Docker" > docker-explanation.txt
qwen -p "Explain Docker" --output-format json > docker-explanation.json
# Append to file
qwen -p "Add more details" >> docker-explanation.txt
# Pipe to other tools
qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python"
# Stream-JSON output for real-time processing
qwen -p "Explain Docker" --output-format stream-json | jq '.type'
qwen -p "Write code" --output-format stream-json --include-partial-messages | jq '.event.type'設定オプション
ヘッドレス使用のための主要なコマンドラインオプション:
| Option | Description | Example |
|---|---|---|
--prompt, -p | ヘッドレスモードで実行 | qwen -p "query" |
--output-format, -o | 出力フォーマットを指定(text, json, stream-json) | qwen -p "query" --output-format json |
--input-format | 入力フォーマットを指定(text, stream-json) | qwen --input-format text --output-format stream-json |
--include-partial-messages | stream-json 出力に部分的なメッセージを含める | qwen -p "query" --output-format stream-json --include-partial-messages |
--system-prompt | この実行のメインセッションシステムプロンプトを上書き | qwen -p "query" --system-prompt "You are a terse reviewer." |
--append-system-prompt | この実行のメインセッションシステムプロンプトに追加指示を付加 | qwen -p "query" --append-system-prompt "Focus on concrete findings." |
--debug, -d | デバッグモードを有効化 | qwen -p "query" --debug |
--all-files, -a | コンテキストにすべてのファイルを含める | qwen -p "query" --all-files |
--include-directories | 追加のディレクトリを含める | qwen -p "query" --include-directories src,docs |
--yolo, -y | すべてのアクションを自動承認 | qwen -p "query" --yolo |
--approval-mode | 承認モードを設定 | qwen -p "query" --approval-mode auto_edit |
--continue | このプロジェクトの最新のセッションを再開 | qwen --continue -p "Pick up where we left off" |
--resume [sessionId] | 特定のセッションを再開(または対話的に選択) | qwen --resume 123e... -p "Finish the refactor" |
利用可能なすべての設定オプション、設定ファイル、環境変数の詳細については、設定ガイド を参照してください。
使用例
コードレビュー
cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txtコミットメッセージの生成
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'API ドキュメント
result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.jsonバッチコード分析
for file in src/*.py; do
echo "Analyzing $file..."
result=$(cat "$file" | qwen -p "Find potential bugs and suggest improvements" --output-format json)
echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
echo "Completed analysis for $(basename "$file")" >> reports/progress.log
donePR コードレビュー
result=$(git diff origin/main...HEAD | qwen -p "Review these changes for bugs, security issues, and code quality" --output-format json)
echo "$result" | jq -r '.response' > pr-review.jsonログ分析
grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txtリリースノートの生成
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
response=$(echo "$result" | jq -r '.response')
echo "$response"
echo "$response" >> CHANGELOG.mdモデルおよびツール使用状況の追跡
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): $total_tokens tokens, $tool_calls tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "Recent usage trends:"
tail -5 usage.log