Tutorials · Claude Agent SDK · examples / python / 12_interrupt.pyExample code

Example code · python

12_interrupt.py

Interrupt a running turn, drain it, then send a new one.

Raw fileDownload all examples (zip)See its output →

Used in Part 1 · Interrupting

"""12: Interrupt a running turn, drain it, then send a new one."""

import asyncio
import time

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, TextBlock, ToolUseBlock
from demo_util import PROJECT


async def main():
    options = ClaudeAgentOptions(cwd=PROJECT, allowed_tools=["Bash"], permission_mode="acceptEdits")
    async with ClaudeSDKClient(options) as client:
        start = time.time()
        await client.query("Count from 1 to 60, one number per second, using `sleep 1` in bash between numbers.")
        await asyncio.sleep(8)
        await client.interrupt()
        print(f"interrupt() sent after {time.time() - start:.1f}s")

        # Drain the interrupted turn BEFORE sending anything else
        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, ToolUseBlock):
                        print(f"  tool call: {block.name}({str(block.input)[:60]})")
            if isinstance(message, ResultMessage):
                print(f"interrupted turn: subtype={message.subtype} terminal_reason={message.terminal_reason!r} "
                      f"after {time.time() - start:.1f}s")

        await client.query("Just say hello instead.")
        async for message in client.receive_response():
            if isinstance(message, ResultMessage):
                print(f"next turn: {message.subtype} -> {message.result!r}")


asyncio.run(main())

36 lines · Back to the folder