The Claude Code SDK for Python allows developers to integrate Claude Code directly into their Python applications. It provides a streamlined interface for sending queries and managing tool calls, removing the need to interact manually with low-level APIs.
npm install -g @anthropic-ai/claude-codeInstall the package using pip:
pip install claude-code-sdk
The following example demonstrates how to send a simple query to Claude and print the output.
import anyio
from claude_code_sdk import query
async def main():
async for message in query(prompt="What is 2 + 2?"):
print(message)
anyio.run(main)
Simple query implementation:
from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock
async for message in query(prompt="Hello Claude"):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
print(block.text)
Query with configuration options:
options = ClaudeCodeOptions(
system_prompt="You are a helpful assistant",
max_turns=1
)
async for message in query(prompt="Tell me a joke", options=options):
print(message)
Grant Claude permission to read files, write data, or execute shell commands.
options = ClaudeCodeOptions(
allowed_tools=["Read", "Write", "Bash"],
permission_mode='acceptEdits' # Automatically approve file modifications
)
async for message in query(
prompt="Create a hello.py file",
options=options
):
# Handle tool usage and resulting output
pass
You can define the project directory where the SDK should operate.
from pathlib import Path
options = ClaudeCodeOptions(
cwd="/path/to/project" # Accepts strings or Path objects
)
query functionSignature: query(prompt, options=None)
Parameters:
prompt (str): The text prompt to send to Claude.options (ClaudeCodeOptions): An optional configuration object.Returns: AsyncIterator[Message] – An asynchronous stream of response messages.
Comprehensive type definitions are located in src/claude_code_sdk/types.py:
ClaudeCodeOptions: Configuration settings for the SDK.AssistantMessage, UserMessage, SystemMessage, ResultMessage: Various message types.TextBlock, ToolUseBlock, ToolResultBlock: Types for different content blocks.The SDK includes several exception types to help manage specific failure states:
from claude_code_sdk import (
ClaudeSDKError, # Base error for the SDK
CLINotFoundError, # Claude Code CLI is not installed
CLIConnectionError, # Issue connecting to the CLI
ProcessError, # The process failed during execution
CLIJSONDecodeError, # Error parsing JSON response
)
try:
async for message in query(prompt="Hello"):
pass
except CLINotFoundError:
print("Error: Please install the Claude Code CLI.")
except ProcessError as e:
print(f"Process failed with exit code: {e.exit_code}")
except CLIJSONDecodeError as e:
print(f"Failed to parse the CLI response: {e}")
For a complete list of error types, refer to src/claude_code_sdk/_errors.py.
Grey Deer VPN: Residential IPs for Secure Global Access
PromptEnhancer: Rewrite Any Prompt for Stunning AI Images
BuildAdmin: Vue3 ThinkPHP8 Panel With Visual CRUD Builder
UTCP Explained: A Universal Tool Calling Protocol for APIs, LLMs, and Beyond
Zotero PDF2zh: Translate Academic PDFs Directly Within Zotero
ACI.dev: 600+ Tools for AI Agents with Built-In Auth and MCP Support
News Agents: Scalable RSS Summarization with Amazon Q and tmux
Turn eBooks & PDFs into Audio with Abogen – Fast TTS Tool
Add Area Fill to Line Charts in Excel: Step-by-Step
How to Install Unregistered Apps on Android
XMIF VPN Free Trial & $0.70/Month Plan – No Logs, 4K Speed
Shendeng VPN: Genuine Unlimited Data & High-Speed Gaming Acceleration