Setting the file. One moment.
Chapter 47 · Instrument Integration
Subchapter 47.26
references/EXAMPLE-python.mdMarkdown12 KBView on GitHub
Repository: https://github.com/PostHog/context-mill Path: basics/python
A simple command-line todo application built with plain Python (no frameworks) demonstrating PostHog integration for CLIs, scripts, data pipelines, and non-web Python applications.
This example serves as:
Posthog(...) class instead of module-level APIshutdown() to flush events before exitdistinct_id and propertiesidentify(), and updates them later with set() and setOnce()# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt# Copy environment template
cp .env.example .env
# Edit .env and add your PostHog project token
# POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
# POSTHOG_HOST=https://us.i.posthog.com# Add a todo
python todo.py add "Buy groceries"
# List all todos
python todo.py list
# Complete a todo
python todo.py complete 1
# Delete a todo
python todo.py delete 1
# Show statistics
python todo.py statsThe app tracks these events in PostHog:
| Event | Properties | Purpose |
|---|---|---|
todo_added | todo_id, todo_length, total_todos | When user adds a new todo |
todos_viewed | total_todos, completed_todos | When user lists todos |
todo_completed | todo_id, time_to_complete_hours | When user completes a todo |
todo_deleted | todo_id, was_completed | When user deletes a todo |
stats_viewed | total_todos, completed_todos, pending_todos | When user views stats |
basics/python/
├── todo.py # Main CLI application
├── requirements.txt # Python dependencies
├── .env.example # Environment variable template
├── .gitignore # Git ignore rules
└── README.md # This filefrom posthog import Posthog
posthog = Posthog(
api_key,
host='https://us.i.posthog.com',
enable_exception_autocapture=True # Automatically capture exceptions
)# Track events with distinct_id
posthog_client.capture(
distinct_id="user_123",
event="event_name",
properties={"key": "value"}
)try:
# Your application code
pass
finally:
# Always call shutdown() to flush events and close connections
posthog.shutdown()# Set person properties on a user profile
posthog_client.set(
distinct_id="user_123",
properties={"email": "user@example.com", "plan": "pro"}
)try:
# Code that might fail
risky_operation()
except Exception as e:
# Manually capture handled errors you want to track
posthog_client.capture_exception(e, distinct_id="user_123")The app works fine without PostHog configured - it simply won’t track analytics. You’ll see a warning message but the app continues to function normally.
todo.py to experiment with PostHog trackingposthog.feature_enabled('flag-name', user_id)# PostHog Configuration
POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
POSTHOG_HOST=https://us.i.posthog.com
# Optional: Enable debug mode to see PostHog requests
# POSTHOG_DEBUG=true
posthog>=3.0.0
python-dotenv>=1.0.0
#!/usr/bin/env python3
"""Simple CLI Todo App with PostHog Analytics
A minimal plain Python CLI application demonstrating PostHog integration
for non-framework Python projects (CLIs, scripts, data pipelines, etc.).
"""
import argparse
import json
import os
import sys
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from posthog import Posthog
# Load environment variables
load_dotenv()