Output Preservation and Error Handling¶
This notebook demonstrates how MkDocs-Jupyter handles various output types and error conditions.
Features Demonstrated¶
- Text outputs (stdout, stderr)
- Rich outputs (HTML, images, plots)
- Error handling and traceback display
- Interactive outputs
- Cell tagging for output control
1. Basic Text Outputs¶
Standard output and print statements are preserved:
In [ ]:
Copied!
# Simple print statements
print("Hello, MkDocs!")
print("This is standard output.")
# Multiple outputs
for i in range(3):
print(f"Iteration {i + 1}")
# Simple print statements
print("Hello, MkDocs!")
print("This is standard output.")
# Multiple outputs
for i in range(3):
print(f"Iteration {i + 1}")
In [ ]:
Copied!
# Returning values
x = 42
y = 3.14159
z = "String output"
# Last expression is displayed
f"x = {x}, y = {y:.2f}, z = '{z}'"
# Returning values
x = 42
y = 3.14159
z = "String output"
# Last expression is displayed
f"x = {x}, y = {y:.2f}, z = '{z}'"
2. Rich HTML Outputs¶
HTML content is rendered properly:
In [ ]:
Copied!
from IPython.display import HTML, display
# Display HTML table
html_content = """
<table style="border-collapse: collapse; width: 100%;">
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #ddd; padding: 8px;">Feature</th>
<th style="border: 1px solid #ddd; padding: 8px;">Status</th>
<th style="border: 1px solid #ddd; padding: 8px;">Description</th>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Output Preservation</td>
<td style="border: 1px solid #ddd; padding: 8px; color: green;">✓ Active</td>
<td style="border: 1px solid #ddd; padding: 8px;">All outputs are preserved</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Error Handling</td>
<td style="border: 1px solid #ddd; padding: 8px; color: green;">✓ Active</td>
<td style="border: 1px solid #ddd; padding: 8px;">Errors are captured gracefully</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Interactive Outputs</td>
<td style="border: 1px solid #ddd; padding: 8px; color: orange;">⚡ Limited</td>
<td style="border: 1px solid #ddd; padding: 8px;">Some interactivity preserved</td>
</tr>
</table>
"""
display(HTML(html_content))
from IPython.display import HTML, display
# Display HTML table
html_content = """
"""
display(HTML(html_content))
Feature | Status | Description |
---|---|---|
Output Preservation | ✓ Active | All outputs are preserved |
Error Handling | ✓ Active | Errors are captured gracefully |
Interactive Outputs | ⚡ Limited | Some interactivity preserved |
In [ ]:
Copied!
# Display styled text
styled_html = """
<div style="background-color: #e8f4f8; padding: 20px; border-radius: 10px; border-left: 4px solid #2196F3;">
<h3 style="color: #1976D2; margin-top: 0;">💡 Important Note</h3>
<p style="color: #424242; margin-bottom: 0;">
MkDocs-Jupyter preserves rich HTML outputs including styling,
making it perfect for creating beautiful documentation with
interactive notebook content.
</p>
</div>
"""
display(HTML(styled_html))
# Display styled text
styled_html = """
"""
display(HTML(styled_html))
💡 Important Note
MkDocs-Jupyter preserves rich HTML outputs including styling, making it perfect for creating beautiful documentation with interactive notebook content.
3. Data Visualization Outputs¶
Plots and charts are preserved as images:
In [ ]:
Copied!
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create figure with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
# First plot
ax1.plot(x, y1, "b-", label="sin(x)")
ax1.plot(x, y2, "r--", label="cos(x)")
ax1.set_title("Trigonometric Functions")
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.legend()
ax1.grid(True, alpha=0.3)
# Second plot - bar chart
categories = ["Text", "HTML", "Plot", "Error", "Widget"]
values = [100, 95, 100, 90, 70]
colors = ["#4CAF50", "#2196F3", "#FF9800", "#F44336", "#9C27B0"]
ax2.bar(categories, values, color=colors)
ax2.set_title("Output Type Support Level (%)")
ax2.set_ylabel("Support Level")
ax2.set_ylim(0, 110)
# Add value labels on bars
for i, (cat, val) in enumerate(zip(categories, values)):
ax2.text(i, val + 2, f"{val}%", ha="center")
plt.tight_layout()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create figure with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
# First plot
ax1.plot(x, y1, "b-", label="sin(x)")
ax1.plot(x, y2, "r--", label="cos(x)")
ax1.set_title("Trigonometric Functions")
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.legend()
ax1.grid(True, alpha=0.3)
# Second plot - bar chart
categories = ["Text", "HTML", "Plot", "Error", "Widget"]
values = [100, 95, 100, 90, 70]
colors = ["#4CAF50", "#2196F3", "#FF9800", "#F44336", "#9C27B0"]
ax2.bar(categories, values, color=colors)
ax2.set_title("Output Type Support Level (%)")
ax2.set_ylabel("Support Level")
ax2.set_ylim(0, 110)
# Add value labels on bars
for i, (cat, val) in enumerate(zip(categories, values)):
ax2.text(i, val + 2, f"{val}%", ha="center")
plt.tight_layout()
plt.show()
4. Error Handling Examples¶
MkDocs-Jupyter can handle errors gracefully when configured with allow_errors: true
:
In [ ]:
Copied!
# This cell will raise an error (division by zero)
# The error is captured and displayed
def divide(a, b):
return a / b
result = divide(10, 0) # This will raise ZeroDivisionError
# This cell will raise an error (division by zero)
# The error is captured and displayed
def divide(a, b):
return a / b
result = divide(10, 0) # This will raise ZeroDivisionError
In [ ]:
Copied!
# Another error example - undefined variable
# This shows how NameError is handled
print(undefined_variable) # This will raise NameError
# Another error example - undefined variable
# This shows how NameError is handled
print(undefined_variable) # This will raise NameError
In [ ]:
Copied!
# Error handling with try-except
# This shows proper error handling
try:
result = 1 / 0
except ZeroDivisionError as e:
print(f"Error caught: {type(e).__name__}")
print(f"Error message: {str(e)}")
print("Handled gracefully!")
# Error handling with try-except
# This shows proper error handling
try:
result = 1 / 0
except ZeroDivisionError as e:
print(f"Error caught: {type(e).__name__}")
print(f"Error message: {str(e)}")
print("Handled gracefully!")
5. Multiple Output Types in One Cell¶
Cells can produce multiple types of output:
In [ ]:
Copied!
# Multiple output types
print("1. Text output via print()")
# DataFrame output
import pandas as pd
df = pd.DataFrame(
{
"Output Type": ["Text", "DataFrame", "Plot", "HTML"],
"Supported": ["Yes", "Yes", "Yes", "Yes"],
"Quality": ["Excellent", "Excellent", "Good", "Excellent"],
}
)
print("\n2. DataFrame output:")
display(df)
# HTML output
print("\n3. HTML output:")
display(HTML("<strong>Bold HTML text</strong> with <em>emphasis</em>"))
# Return value
"4. Return value (last expression)"
# Multiple output types
print("1. Text output via print()")
# DataFrame output
import pandas as pd
df = pd.DataFrame(
{
"Output Type": ["Text", "DataFrame", "Plot", "HTML"],
"Supported": ["Yes", "Yes", "Yes", "Yes"],
"Quality": ["Excellent", "Excellent", "Good", "Excellent"],
}
)
print("\n2. DataFrame output:")
display(df)
# HTML output
print("\n3. HTML output:")
display(HTML("Bold HTML text with emphasis"))
# Return value
"4. Return value (last expression)"
6. Cell Tag Demonstrations¶
The following cells demonstrate tag-based output control:
In [ ]:
Copied!
# This cell has the 'hide-output' tag
# Only the code will be shown, not the output
print("This output is hidden!")
print("You can see the code but not what it produces.")
# This is useful for setup code or examples where
# you want to show the code but not clutter with output
# This cell has the 'hide-output' tag
# Only the code will be shown, not the output
print("This output is hidden!")
print("You can see the code but not what it produces.")
# This is useful for setup code or examples where
# you want to show the code but not clutter with output
7. Progress Indicators and Streaming Output¶
Demonstrating how streaming outputs are captured:
In [ ]:
Copied!
import sys
import time
# Simulated progress indicator
print("Processing data...")
for i in range(5):
print(f"Step {i+1}/5 completed", end="")
for j in range(3):
time.sleep(0.1) # Simulate work
print(".", end="", flush=True)
print() # New line
print("\nProcessing complete!")
import sys
import time
# Simulated progress indicator
print("Processing data...")
for i in range(5):
print(f"Step {i+1}/5 completed", end="")
for j in range(3):
time.sleep(0.1) # Simulate work
print(".", end="", flush=True)
print() # New line
print("\nProcessing complete!")
8. Summary and Best Practices¶
Output Preservation Features¶
- All standard outputs are preserved: print statements, return values, displays
- Rich outputs are supported: HTML, images, plots, DataFrames
- Errors are handled gracefully: Tracebacks are formatted nicely
- Cell tags control visibility: hide-input, hide-output, hide-cell
Best Practices¶
- Use
display()
for rich outputs: Ensures proper rendering - Handle errors explicitly: Use try-except for expected errors
- Tag cells appropriately: Hide implementation details when needed
- Test notebook execution: Ensure all cells run without unexpected errors
- Clear outputs before committing: Keep version control clean
Configuration Tips¶
plugins:
- mkdocs-jupyter:
execute: true # Execute notebooks
allow_errors: true # Don't fail on errors
show_input: true # Show code by default
include_requirejs: true # For interactive outputs