Runtime documentation generation tool for live markdown output
Project description
DocPrint Reference Guide
Overview
DocPrint is a runtime documentation generation tool that creates live markdown output with intelligent caching, content deduplication, and optional GitHub integration.
Installation
pip install docprint
Optional performance dependencies:
pip install docprint[performance] # Includes ujson, orjson
Manual performance installation:
pip install regex xxhash orjson
Quick Start
from docprint import docPrint, flush_cache, docPrintFile, enableGitCommits
# Basic usage - writes to DOC.PRINT.md
docPrint('text', 'Status', 'Application started')
# Custom output file
docPrintFile("my_docs.md")
docPrint('header', 'Project Status', 'Ready for deployment')
# Optional GitHub integration
enableGitCommits(True, token="ghp_xxx", repo="user/repo")
# Automatic flushing every 30 seconds or 1000 calls
# Manual flush when needed
flush_cache()
GitHub Integration
Auto-sync Documentation
Automatically push documentation changes to GitHub at configurable intervals.
from docprint import enableGitCommits, docPrint
import os
# Enable GitHub sync (requires personal access token)
enableGitCommits(True, token="ghp_xxx", repo="username/repository")
# Custom sync interval (minimum 1 minute)
enableGitCommits(True,
token="ghp_xxx",
repo="username/repository",
interval_minutes=5)
# Disable sync
enableGitCommits(False)
Setup Requirements
- GitHub personal access token with repo permissions
- Target repository must exist and be accessible
- Respects API rate limits (1 request per minute maximum)
Behavior
- Only pushes when content actually changes
- Uses content hashing to detect modifications
- Creates single commit per sync with message:
docs: update {filename} via DocPrint - Handles network failures gracefully
- Thread-safe operation
Token Setup
Environment variable (recommended):
export GITHUB_TOKEN=ghp_xxxxxxxxxxxx
Direct usage:
import os
token = os.getenv('GITHUB_TOKEN')
enableGitCommits(True, token=token, repo="user/repo")
Direct token (less secure):
enableGitCommits(True, token="ghp_xxx", repo="user/repo")
Error Handling
try:
enableGitCommits(True, token="invalid", repo="test/repo")
except ValueError as e:
print(f"GitHub setup failed: {e}")
Usage Examples
Basic automation:
# Set up once at startup
enableGitCommits(True,
token=os.getenv('GITHUB_TOKEN'),
repo="company/docs")
# Normal operation - auto-syncs every minute
docPrint('text', 'Server Status', 'Running')
docPrint('table', 'Metrics', performance_data)
# Changes sync automatically
Development workflow:
# During development - faster sync
enableGitCommits(True,
token=token,
repo="dev/project-docs",
interval_minutes=2)
# Production - slower sync to reduce API calls
enableGitCommits(True,
token=token,
repo="prod/documentation",
interval_minutes=10)
Conditional sync:
# Only enable in production
if os.getenv('ENVIRONMENT') == 'production':
enableGitCommits(True,
token=os.getenv('GITHUB_TOKEN'),
repo="company/live-docs")
File Management
Default Output
By default, all content is written to DOC.PRINT.md in the current directory.
Custom Output Files
# Single file
docPrintFile("documentation.md")
# Create directory structure
docPrintFile("logs/app.log")
docPrintFile("reports/daily/status.md")
docPrintFile("project/docs/api.md")
# Reset to default
docPrintFile("") # Returns to DOC.PRINT.md
File switching:
- Flushes current cache before switching files
- Creates directories automatically
- Thread-safe file operations
- Atomic file writes prevent corruption
Available Formatters
Basic Content Types
Header
docPrint('header', 'Section Title', 'Optional description')
Section Title
Optional description
Text
docPrint('text', 'Status', 'System operational', line=True)
Status
System operational
Table
docPrint('table', 'Performance Data', [
{'metric': 'CPU', 'value': '45%'},
{'metric': 'Memory', 'value': '2.1GB'}
])
Performance Data
| metric | value |
|---|---|
| CPU | 45% |
| Memory | 2.1GB |
Table with Alignment
docPrint('advanced_table', 'User Data', {
'headers': ['Name', 'Age', 'Score'],
'alignment': ['left', 'center', 'right'],
'rows': [
['Alice', 25, 95.5],
['Bob', 30, 88.2],
['Charlie', 28, 92.0]
]
})
User Data
| Name | Age | Score |
|---|---|---|
| Alice | 25 | 95.5 |
| Bob | 30 | 88.2 |
| Charlie | 28 | 92.0 |
Structural Elements
Bullets
docPrint('bullets', 'Key Points', ['First point', 'Second point', 'Third point'])
Key Points
- First point
- Second point
- Third point
Horizontal Rule
docPrint('horizontal_rule', 'Section Break', 'Content above the line')
Section Break
Content above the line
Code Block
docPrint('code_block', 'Python Example', 'print("Hello World")', language='python')
Python Example
print("Hello World")
Blockquote
docPrint('blockquote', 'Quote', 'This is important text')
Quote
This is important text
Ordered List
docPrint('ordered_list', 'Steps', ['Step 1', 'Step 2', 'Step 3'])
Steps
- Step 1
- Step 2
- Step 3
Unordered List
docPrint('unordered_list', 'Items', ['Item A', 'Item B', 'Item C'])
Items
- Item A
- Item B
- Item C
Footnotes
docPrint('footnotes', 'Research Paper',
("This study builds on previous work",
{1: "Source: Smith et al. 2020", 2: "Additional data from Johnson study"}))
Research Paper
This study builds on previous work[^1][^2]
[^1]: Source: Smith et al. 2020 [^2]: Additional data from Johnson study
Definition List
docPrint('definition_list', 'Glossary', {
"API": "Application Programming Interface",
"JSON": "JavaScript Object Notation"
})
Glossary
API : Application Programming Interface
JSON : JavaScript Object Notation
Task List
docPrint('task_list', 'Checklist', [
{"task": "Write documentation", "completed": True},
{"task": "Test features", "completed": False}
])
Checklist
- Write documentation
- Test features
Visual Elements
Badge
docPrint('badge', 'Build Status', {
'label': 'build',
'message': 'passing',
'color': 'green',
'style': 'flat',
'url': 'https://github.com/repo'
})
Build Status
HTML Block
docPrint('html_block', 'Custom HTML', {
'tag': 'div',
'attributes': {'class': 'highlight', 'id': 'test-div'},
'content': 'This is custom HTML content'
})
Custom HTML
CSS Block
docPrint('css_block', 'Styling', {
'selector': '.highlight',
'styles': {
'background-color': 'yellow',
'padding': '10px',
'border-radius': '5px'
}
})
Styling
.highlight {
background-color: yellow;
padding: 10px;
border-radius: 5px;
}
SVG Animation
docPrint('svg_animation', 'Loading Spinner', {
'width': 50,
'height': 50,
'elements': [{
'tag': 'circle',
'attributes': {'cx': 25, 'cy': 25, 'r': 10, 'fill': 'blue'},
'animations': [{
'attributeName': 'r',
'values': '5;15;5',
'dur': '1s',
'repeatCount': 'indefinite'
}]
}]
})
Loading Spinner
Rich Content
Alert
docPrint('alert', 'Warning', 'This is important', alert_type='warning')
docPrint('alert', 'Error List', ['Error 1', 'Error 2'], alert_type='error')
Alert types: info, warning, error, success, note
Warning
[WARNING]
This is important
Error List
[ERROR]
Error 1 Error 2
Collapsible Section
docPrint('collapsible', 'Details', 'Hidden content', summary='Click to expand')
Details
Click to expand
Hidden content
Image
docPrint('image', 'Logo', {
'url': 'https://example.com/logo.png',
'alt': 'Company Logo',
'title': 'Our Logo',
'width': '200',
'height': '100'
})
# Simple version
docPrint('image', 'Simple Image', 'https://example.com/image.jpg')
Logo
Simple Image
Link Collection
docPrint('link_collection', 'Resources', [
{'url': 'https://github.com', 'text': 'GitHub', 'description': 'Code repository'},
{'url': 'https://docs.python.org', 'text': 'Python Docs'}
])
Resources
- GitHub - Code repository
- Python Docs
Function Reference
docPrint(section_type, header, content="", line=True, **kwargs)
Generate and cache formatted content.
Parameters:
section_type: Formatter to use (see Available Formatters)header: Section header textcontent: Main content (string, list, or dict depending on type)line: Add separator line after content (default: True)**kwargs: Type-specific parameters
Type-specific Parameters:
language: Code block syntax highlightingalert_type: Alert style (info, warning, error, success, note)summary: Collapsible section summary textalignment: Table column alignment (['left', 'center', 'right'])
docPrintFile(filepath)
Set output file for subsequent docPrint calls.
Parameters:
filepath: Target file path (creates directories as needed)- Empty string or None resets to default (DOC.PRINT.md)
flush_cache()
Force write cached content to file immediately.
enableGitCommits(enabled, **kwargs)
Enable or disable automatic GitHub synchronization.
Parameters:
enabled: Boolean to enable/disable GitHub synctoken: GitHub personal access token (required when enabled)repo: Repository in format "username/repository" (required when enabled)interval_minutes: Sync interval in minutes, minimum 1 (default: 1)
Examples:
# Enable with defaults
enableGitCommits(True, token="ghp_xxx", repo="user/repo")
# Custom interval
enableGitCommits(True, token="ghp_xxx", repo="user/repo", interval_minutes=5)
# Disable
enableGitCommits(False)
Raises:
ValueError: Invalid token, repository access denied, or missing parametersImportError: GitHub integration not available (should not occur in normal installations)
Notes:
- Validates repository access before enabling
- Only one sync configuration active at a time
- Disabling clears any existing sync timers
- Changes sync to currently configured output file
Performance Features
Smart Caching
- Content deduplication: Identical content is automatically deduplicated
- Hash-based comparison: Uses xxhash (fast) or MD5 (fallback) for content comparison
- Zero redundant I/O: Repeated identical content doesn't trigger file writes
Optimized I/O
- Memory-mapped files: Large files (>1MB) use mmap for better performance
- Atomic writes: Temporary files with atomic replacement prevent corruption
- Thread-safe operations: RLock protection for concurrent access
- Efficient path operations: Uses pathlib.Path for cross-platform compatibility
Auto-flush Behavior
- Time-based: Every 30 seconds
- Count-based: Every 1000 docPrint calls
- Only when needed: Empty cache skips I/O operations
Content Management
Content Updates
Sections with the same header are automatically updated in place:
docPrint('text', 'Status', 'Starting up')
# Later...
docPrint('text', 'Status', 'Running') # Updates existing section
Multi-file Documentation
# API documentation
docPrintFile("docs/api.md")
docPrint('header', 'REST API', 'Version 2.0')
docPrint('code_block', 'Authentication', auth_example, language='python')
# Separate log file
docPrintFile("logs/errors.log")
docPrint('alert', 'Database Error', error_details, alert_type='error')
# Back to main docs
docPrintFile("README.md")
docPrint('header', 'Project Overview', project_description)
Configuration
Located in docprint.config.constants:
CACHE_FLUSH_INTERVAL = 30 # Auto-flush interval (seconds)
CACHE_FLUSH_COUNT = 1000 # Auto-flush threshold (calls)
DOC_FILE_PREFIX = "DOC.PRINT" # Default file prefix
DOC_FILE_EXTENSION = ".md" # Default file extension
DEFAULT_OUTPUT_DIR = "." # Default output directory
Dependencies
Core dependencies:
regex>=2025.9.1- Fast pattern matchingxxhash>=3.5.0- Fast content hashing
Optional performance dependencies:
ujson>=5.11.0- Fast JSON operations for GitHub APIorjson>=3.11.3- Fastest JSON operations (when available)
GitHub integration notes:
- Zero overhead when GitHub sync is disabled
- Uses standard library urllib when performance packages unavailable
- Fallback JSON handling maintains compatibility
Thread Safety
DocPrint is fully thread-safe:
- RLock protection for cache operations
- Atomic file writes prevent corruption
- Safe concurrent access to all functions
- Thread-safe file switching
Production Usage
import logging
from docprint import docPrint, docPrintFile
# Application startup
docPrintFile("logs/application.md")
docPrint('header', 'Application Startup', f'Started at {datetime.now()}')
# During operation (automatic caching and flushing)
def process_data(data):
docPrint('text', 'Processing Status', f'Processed {len(data)} items')
if errors:
docPrint('alert', 'Processing Errors', errors, alert_type='error')
# No manual flush needed - auto-flush handles it
# Clean shutdown (optional manual flush)
def shutdown():
docPrint('text', 'Shutdown', 'Application stopped gracefully')
flush_cache() # Ensure final content is written
DocPrint is designed for minimal overhead in production environments with intelligent caching that scales with actual content changes, not call frequency.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file docprint-1.1.1.tar.gz.
File metadata
- Download URL: docprint-1.1.1.tar.gz
- Upload date:
- Size: 16.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5a80f9a5fde9b8ce52a6b1da216fb96313e707d0f755fef2b29133722eea83da
|
|
| MD5 |
eb2f9eb7195d99b4fe7da24947fd4fa8
|
|
| BLAKE2b-256 |
6a0a308400f734d0f4a6df1e9773485d2288efd662e5a1edc344aafaf19265c2
|
File details
Details for the file docprint-1.1.1-py3-none-any.whl.
File metadata
- Download URL: docprint-1.1.1-py3-none-any.whl
- Upload date:
- Size: 22.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d10c0b1d225cb1c9cff3bfeff069fce135e7ede5bbb83cccec05f2b369c3143c
|
|
| MD5 |
2d75a233f8de150e4bd84d25b49035bf
|
|
| BLAKE2b-256 |
16415f5176f8bb47b7beea6c9e0ec27b864b362f35f137a2853c75f645bcc302
|