> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/QwenLM/qwen-code/llms.txt
> Use this file to discover all available pages before exploring further.

# --prompt Option

> Execute Qwen Code in non-interactive (headless) mode

## Overview

The `--prompt` (or `-p`) option runs Qwen Code in non-interactive mode, executing a single prompt and exiting. This is ideal for automation, scripting, and CI/CD pipelines.

## Syntax

```bash theme={null}
qwen --prompt "Your prompt here"
qwen -p "Your prompt here"
```

## Basic Usage

### Single Command

```bash theme={null}
qwen --prompt "Create a Python function to calculate factorial"
```

Output:

```python theme={null}
def factorial(n):
    """Calculate the factorial of n."""
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)
```

### Code Generation

```bash theme={null}
qwen --prompt "Write a REST API endpoint for user authentication"
```

### Code Review

```bash theme={null}
qwen --prompt "Review the code in src/auth.ts for security issues"
```

## Piping Input

Combine stdin with the prompt:

```bash theme={null}
# Read file and append prompt
cat mycode.py | qwen --prompt "Add type hints to this code"

# Git diff review
git diff | qwen --prompt "Review these changes"

# Error analysis
npm test 2>&1 | qwen --prompt "Explain these test failures"
```

The stdin content is automatically prepended to your prompt.

## Output Formats

### Text Output (Default)

Human-readable output:

```bash theme={null}
qwen --prompt "Hello" --output-format text
```

### JSON Output

Structured output for parsing:

```bash theme={null}
qwen --prompt "Generate a user model" --output-format json
```

Output:

```json theme={null}
{
  "type": "result",
  "isError": false,
  "messages": [
    {
      "role": "assistant",
      "content": "Here's a user model..."
    }
  ],
  "usage": {
    "inputTokens": 123,
    "outputTokens": 456,
    "totalTokens": 579
  },
  "durationMs": 2341
}
```

### Stream JSON Output

Real-time streaming events:

```bash theme={null}
qwen --prompt "Build a React app" --output-format stream-json
```

Outputs newline-delimited JSON events:

```json theme={null}
{"type":"system_message","session_id":"abc123",...}
{"type":"assistant_message_start",...}
{"type":"content","value":"I'll help you build a React app..."}
{"type":"tool_call_request","name":"write",...}
{"type":"assistant_message_end",...}
{"type":"result","isError":false,...}
```

## Combining with Other Options

### With Model Selection

```bash theme={null}
qwen --prompt "Complex refactoring task" --model qwen-coder-plus
```

### With YOLO Mode

Auto-approve all actions:

```bash theme={null}
qwen --yolo --prompt "Fix all linting errors in the project"
```

### With Session Management

```bash theme={null}
# Continue previous session
qwen --continue --prompt "Now add tests for that function"

# Use specific session
qwen --resume abc123 --prompt "Update the authentication"
```

### With Approval Mode

```bash theme={null}
# Plan only, no execution
qwen --approval-mode plan --prompt "Refactor the codebase"

# Auto-approve edits only
qwen --approval-mode auto-edit --prompt "Update all imports"
```

## Slash Commands in Prompts

You can use slash commands in headless mode:

```bash theme={null}
# Compress context
qwen --prompt "/compress"

# Generate project summary
qwen --prompt "/summary"

# View statistics
qwen --prompt "/stats"
```

<Note>
  Only certain slash commands work in non-interactive mode. Commands requiring user interaction (like `/auth`, `/model`) are not supported.
</Note>

## Automation Examples

### CI/CD Pipeline

```bash theme={null}
#!/bin/bash
# .github/workflows/ai-review.sh

set -e

# Get changed files
FILES=$(git diff --name-only origin/main...HEAD)

# Review each file
for file in $FILES; do
  echo "Reviewing $file..."
  qwen --prompt "Review $file for issues" --output-format json > "review-$file.json"
done

# Aggregate results
echo "Review complete. Check review-*.json files."
```

### Code Generation Script

```bash theme={null}
#!/bin/bash
# generate-tests.sh

for file in src/**/*.ts; do
  if [[ ! -f "${file%.ts}.test.ts" ]]; then
    echo "Generating tests for $file"
    qwen --yolo --prompt "Create comprehensive unit tests for $file"
  fi
done
```

### Documentation Generator

```bash theme={null}
#!/bin/bash
# generate-docs.sh

qwen --prompt "Generate API documentation for all files in src/api/" \
     --output-format json \
     | jq -r '.messages[] | select(.role=="assistant") | .content' \
     > API_DOCS.md

echo "Documentation generated in API_DOCS.md"
```

### Error Analyzer

```bash theme={null}
#!/bin/bash
# analyze-errors.sh

# Run tests and capture errors
ERRORS=$(npm test 2>&1 || true)

# Analyze with AI
echo "$ERRORS" | qwen --prompt "Analyze these test failures and suggest fixes" \
                       --output-format text
```

## Interactive vs Non-Interactive

### Use `--prompt` When:

✅ Running in scripts or CI/CD\
✅ One-shot commands\
✅ Automated workflows\
✅ Piping data through Qwen Code\
✅ Need programmatic output (JSON)

### Use Interactive Mode When:

✅ Exploratory work\
✅ Complex, multi-step tasks\
✅ Need to approve actions\
✅ Iterative development\
✅ Want conversation history

## Prompt Engineering

### Be Specific

```bash theme={null}
# Vague
qwen --prompt "Fix the bug"

# Specific
qwen --prompt "Fix the null pointer exception in src/auth.ts line 45"
```

### Provide Context

```bash theme={null}
# Better with context
qwen --prompt "This is a React TypeScript project. Add error boundaries to all routes."
```

### Use Clear Instructions

```bash theme={null}
qwen --prompt "Do the following:
1. Read all files in src/
2. Find unused imports
3. Remove them
4. Run linter to verify"
```

## Error Handling

### Check Exit Codes

```bash theme={null}
qwen --prompt "Do something" && echo "Success" || echo "Failed"

# In scripts
if qwen --prompt "Task" --output-format json > result.json; then
  echo "AI task completed successfully"
else
  echo "AI task failed with exit code $?"
  exit 1
fi
```

### Parse JSON Errors

```bash theme={null}
RESULT=$(qwen --prompt "Task" --output-format json)

if echo "$RESULT" | jq -e '.isError' > /dev/null; then
  ERROR_MSG=$(echo "$RESULT" | jq -r '.errorMessage')
  echo "Error: $ERROR_MSG"
  exit 1
fi
```

## Advanced Usage

### Multi-line Prompts

```bash theme={null}
# Using heredoc
qwen --prompt "$(cat <<'EOF'
Create a REST API with the following endpoints:
- GET /users - List all users
- POST /users - Create user
- GET /users/:id - Get user
- PUT /users/:id - Update user
- DELETE /users/:id - Delete user

Use Express.js and TypeScript.
EOF
)"
```

### Prompt from File

```bash theme={null}
# Store complex prompts in files
qwen --prompt "$(cat prompts/generate-api.txt)"
```

### Chaining Commands

```bash theme={null}
# Generate, then test, then commit
qwen --yolo --prompt "Add logging to auth.ts" && \
npm test && \
git add auth.ts && \
git commit -m "Add logging"
```

### Conditional Execution

```bash theme={null}
# Only run if tests fail
npm test || qwen --prompt "Fix the failing tests" --yolo
```

## Output Processing

### Extract Code Blocks

````bash theme={null}
qwen --prompt "Create a function" | \
  sed -n '/```python/,/```/p' | \
  sed '1d;$d' > output.py
````

### Parse JSON Output

```bash theme={null}
# Get token usage
qwen --prompt "Task" --output-format json | \
  jq '.usage.totalTokens'

# Get assistant response
qwen --prompt "Question" --output-format json | \
  jq -r '.messages[] | select(.role=="assistant") | .content'

# Check for errors
qwen --prompt "Task" --output-format json | \
  jq -e '.isError == false' > /dev/null
```

### Stream Processing

```bash theme={null}
# Process streaming output
qwen --prompt "Large task" --output-format stream-json | \
  while IFS= read -r line; do
    TYPE=$(echo "$line" | jq -r '.type')
    case $TYPE in
      "content")
        echo "$line" | jq -r '.value'
        ;;
      "tool_call_request")
        echo "Calling tool: $(echo "$line" | jq -r '.name')"
        ;;
    esac
  done
```

## Performance Tips

### Use Faster Models

For simple tasks:

```bash theme={null}
qwen --model qwen-turbo --prompt "Quick question"
```

### Limit Output

```bash theme={null}
qwen --prompt "List files in src/ (max 10)" --max-tokens 500
```

### Parallel Execution

```bash theme={null}
# Process multiple files in parallel
find src/ -name '*.ts' | xargs -P 4 -I {} \
  qwen --prompt "Add JSDoc to {}" --yolo
```

## Limitations

### No Interactive Features

These features don't work in headless mode:

❌ Model selection dialog (`/model`)\
❌ Authentication dialog (`/auth`)\
❌ Session picker (`--resume` without ID)\
❌ Manual approval prompts\
❌ Terminal UI navigation

### Workarounds

```bash theme={null}
# Instead of /model dialog:
qwen --model qwen-coder-plus --prompt "Task"

# Instead of /auth dialog:
qwen --auth-type openai --openai-api-key "$KEY" --prompt "Task"

# Instead of approval prompts:
qwen --yolo --prompt "Task"  # Auto-approve
qwen --approval-mode plan --prompt "Task"  # Plan only
```

## Troubleshooting

### No Output

If there's no output:

```bash theme={null}
# Check if running interactively
qwen --prompt "Test" --output-format text

# Enable debug mode
qwen --debug --prompt "Test"
```

### Hanging

If the command hangs:

```bash theme={null}
# Set timeout (requires timeout command)
timeout 60 qwen --prompt "Task"

# Use Ctrl+C to cancel
```

### Encoding Issues

```bash theme={null}
# Force UTF-8
export LANG=en_US.UTF-8
qwen --prompt "Task with émojis"
```

## See Also

<CardGroup cols={2}>
  <Card title="--prompt-interactive" icon="message-arrow-up" href="/cli/options/prompt-interactive">
    Execute prompt then continue interactively
  </Card>

  <Card title="--yolo" icon="forward-fast" href="/cli/options/yolo">
    Auto-approve all actions
  </Card>

  <Card title="Headless Mode" icon="code" href="/features/headless-mode">
    Complete guide to headless mode
  </Card>

  <Card title="Output Formats" icon="file-code" href="/advanced/output-formats">
    Working with different output formats
  </Card>
</CardGroup>
