Introducing the Claude Code SDK for Python: Streamline Your AI-Powered Coding Workflow
Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster through natural-language commands. By integrating directly with your development environment, Claude Code lets you perform code edits, run tests, search git history, and even commit changes—all without leaving the CLI (docs.anthropic.com, docs.anthropic.com).
The Claude Code SDK for Python provides a simple, idiomatic interface to this powerful tool. Under the hood, it implements Anthropic’s Model Context Protocol (MCP), enabling seamless communication between your Python scripts and the Claude agent (en.wikipedia.org). Whether you’re building custom automation, CI/CD integrations, or interactive notebooks, the SDK makes it easy to embed Claude Code into any Python-based workflow.
Installation & Prerequisites
To get started, ensure you have:
- Python 3.10+
- Node.js (for the underlying
claude-codeCLI) - Claude Code installed globally via NPM:
npm install -g @anthropic-ai/claude-code
Then install the Python SDK:
pip install claude-code-sdk
Quick Start Example
Once installed, you can kick off an asynchronous conversation with Claude directly from Python:
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)
This will stream back message objects—each containing text, tool-use blocks, or file edits—that you can inspect or act upon programmatically (github.com).
Advanced Usage & Configuration
The SDK exposes a variety of options via ClaudeCodeOptions:
system_prompt: Customize Claude’s role (e.g., “You are a helpful assistant”).allowed_tools: Restrict which tools (e.g.,["Read","Write","Bash"]) Claude can invoke.permission_mode: Control how file edits are handled (acceptEdits,rejectEdits, or manual review).cwd: Set a working directory so Claude can operate on a specific codebase.
Here’s an example that auto-accepts edits and constrains Claude to file operations:
from claude_code_sdk import query, ClaudeCodeOptions
options = ClaudeCodeOptions(
allowed_tools=["Read", "Write", "Bash"],
permission_mode="acceptEdits",
cwd="/path/to/project"
)
async for message in query(prompt="Refactor utils.py for readability", options=options):
# Process the file edits as needed
pass
Error Handling
The SDK surfaces specific exceptions for robust error handling:
CLINotFoundErrorif theclaude-codeCLI isn’t installedCLIConnectionErrorfor connectivity failuresProcessErrorwhen the underlying process exits non-zeroCLIJSONDecodeErrorfor malformed JSON responses
from claude_code_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError
try:
async for _ in query(prompt="Hello"):
pass
except CLINotFoundError:
print("Please install Claude Code via npm")
except ProcessError as e:
print(f"Process failed with exit code {e.exit_code}")
except CLIJSONDecodeError:
print("Received invalid JSON from Claude Code")
Further Resources
- Official SDK Documentation: https://docs.anthropic.com/en/docs/claude-code/overview
- GitHub Repository: https://github.com/anthropics/claude-code-sdk-python
- Claude Code Best Practices: Tips on structuring your repo with a
CLAUDE.mdand crafting effective prompts. https://docs.anthropic.com/en/docs/claude-code/best-practices
With the Claude Code SDK for Python, you can automate complex coding tasks, integrate AI assistance into your pipelines, and accelerate development—all through familiar Python code. Give it a try today and transform how you build software!


沪公网安备31011502017015号