Auto-generate API documentation for Python projects with support for multiple docstring formats, type annotations, and customizable templates.
—
Command-line tools for generating documentation, running development servers, and integrating pdoc3 into build systems and workflows.
Primary command-line interface with comprehensive argument parsing and processing.
def main(_args=None) -> None:
"""
Command-line entry point for pdoc3.
Parameters:
- _args: Optional list of command line arguments (defaults to sys.argv)
Supports modes:
- HTML generation (--html)
- PDF/Markdown generation (--pdf)
- HTTP development server (--http)
- Text output (default)
"""Built-in HTTP server for real-time documentation preview during development.
class _WebDoc(BaseHTTPRequestHandler):
def do_GET(self):
"""
Handle GET requests for documentation pages.
Features:
- Live reload on file changes
- Module import path resolution
- Template rendering with error handling
- Search functionality
"""
def do_HEAD(self):
"""
Handle HEAD requests with ETag support for caching.
Returns:
- 200: Page exists and is current
- 304: Page unchanged (ETag match)
- 404: Module not found
- 205: Page modified, needs refresh
"""
def html(self) -> str:
"""
Generate HTML for the requested documentation page.
Returns:
str: Rendered HTML documentation
"""
def resolve_ext(self, import_path: str) -> str:
"""
Resolve external documentation links.
Parameters:
- import_path: Module import path
Returns:
str: Resolved external URL or local path
"""
# Class properties
args: argparse.Namespace # Command line arguments
template_config: Dict[str, Any] # Template configurationFunctions for organizing and writing documentation files to the filesystem.
def module_path(m: 'Module', ext: str) -> str:
"""
Get filesystem path for module documentation output.
Parameters:
- m: Module documentation object
- ext: File extension ('.html', '.md', etc.)
Returns:
str: Output file path
"""
def recursive_write_files(m: 'Module', ext: str, **kwargs) -> None:
"""
Recursively write documentation files for module and submodules.
Parameters:
- m: Module documentation object
- ext: File extension for output files
- **kwargs: Template configuration options
Creates:
- Documentation files for module and all submodules
- Directory structure matching module hierarchy
- Index files for packages
"""Generate search indices for client-side documentation search functionality.
def _generate_lunr_search(modules: List['Module'], index_docstrings: bool,
template_config: Dict[str, Any]) -> None:
"""
Generate Lunr.js search index for documentation.
Parameters:
- modules: List of module documentation objects
- index_docstrings: If True, include docstrings in search index
- template_config: Template configuration dictionary
Creates:
- search.js with Lunr.js search index
- Client-side search functionality
"""Global configuration objects and constants for command-line processing.
# Argument parser with all command-line options
parser: argparse.ArgumentParser
# Global arguments namespace
args: argparse.Namespace
# Server defaults
DEFAULT_HOST: str = 'localhost'
DEFAULT_PORT: int = 8080# Generate HTML documentation
pdoc mymodule --html
# Generate documentation for multiple modules
pdoc module1 module2 module3 --html --output-dir ./docs
# Generate plain text documentation (default)
pdoc mymodule
# Generate PDF-ready Markdown
pdoc mymodule --pdf > mymodule.md# Start development server on default port (8080)
pdoc mymodule --http :
# Start server on custom host and port
pdoc mymodule --http localhost:3000
# Multiple modules with server
pdoc package1 package2 --http :8080# Custom output directory
pdoc mymodule --html --output-dir ./documentation
# Force overwrite existing files
pdoc mymodule --html --force
# Custom template directory
pdoc mymodule --html --template-dir ./templates
# Filter documentation (case-sensitive)
pdoc mymodule --html --filter "public,api"
# Skip import errors and continue
pdoc problematic_module --html --skip-errors
# Close stdin before importing (for problematic modules)
pdoc mymodule --html --close-stdin# Override template options via command line
pdoc mymodule --html -c show_source=True -c external_links=True
# Multiple configuration options
pdoc mymodule --html \
-c show_source=True \
-c latex_math=True \
-c google_search_query="site:mydocs.com" \
-c git_link_template="https://github.com/user/repo/blob/main/{path}#L{start_line}"from pdoc.cli import main
# Generate HTML documentation
main(['mypackage', '--html', '--output-dir', './docs'])
# Generate with custom configuration
main([
'mypackage',
'--html',
'--template-dir', './custom-templates',
'-c', 'show_source=True',
'-c', 'external_links=True'
])from pdoc.cli import main
import subprocess
# Start development server in background
def start_dev_server(modules, port=8080):
"""Start development server for documentation preview."""
args = modules + ['--http', f':{port}']
main(args)
# Generate final documentation
def build_docs(modules, output_dir='./docs'):
"""Build final HTML documentation."""
main(modules + ['--html', '--output-dir', output_dir, '--force'])
# Example usage
modules = ['mypackage.core', 'mypackage.utils', 'mypackage.api']
# Development
start_dev_server(modules, 8080)
# Production build
build_docs(modules, './dist/docs')from pdoc.cli import main
import os
def generate_all_docs(package_root, output_root):
"""Generate documentation for all Python packages in directory."""
for item in os.listdir(package_root):
package_path = os.path.join(package_root, item)
if os.path.isdir(package_path) and os.path.exists(os.path.join(package_path, '__init__.py')):
output_dir = os.path.join(output_root, item)
try:
main([
package_path,
'--html',
'--output-dir', output_dir,
'--force',
'--skip-errors'
])
print(f"Generated docs for {item}")
except Exception as e:
print(f"Failed to generate docs for {item}: {e}")
# Usage
generate_all_docs('./src/packages', './docs')# setup.py integration
from setuptools import setup
from pdoc.cli import main
class BuildDocsCommand:
"""Custom command to build documentation."""
def run(self):
main([
'mypackage',
'--html',
'--output-dir', './docs',
'--template-dir', './doc-templates',
'-c', 'show_source=True'
])
# Makefile integration
def make_docs():
"""Function callable from Makefile."""
main([
'myproject',
'--html',
'--output-dir', './build/docs',
'--force'
])
if __name__ == '__main__':
make_docs()from pdoc.cli import main
import sys
def safe_generate_docs(modules, **kwargs):
"""Generate documentation with comprehensive error handling."""
base_args = ['--html', '--skip-errors']
# Add configuration options
for key, value in kwargs.items():
base_args.extend(['-c', f'{key}={value}'])
try:
main(modules + base_args)
return True
except Exception as e:
print(f"Documentation generation failed: {e}", file=sys.stderr)
return False
# Usage with fallback
success = safe_generate_docs(
['mypackage'],
output_dir='./docs',
show_source=True,
external_links=True
)
if not success:
print("Falling back to basic text documentation")
main(['mypackage']) # Generate plain text as fallbackInstall with Tessl CLI
npx tessl i tessl/pypi-pdoc3