markdown-exec
markdown-exec is a Python library that provides utilities to execute code blocks directly within Markdown files. It's commonly used with MkDocs and PyMdown-Extensions to inject dynamic content, such as script outputs or interactive elements, into documentation. The library sees active development with releases typically occurring every few months.
Warnings
- breaking Support for Python 3.8 was dropped in version 1.10.0. Users on Python 3.8 or older must upgrade their Python environment or remain on an older version of markdown-exec.
- gotcha When using the `pyodide` fence or other fences requiring asset inclusion, configuring `pymdownx.superfences` directly (without the MkDocs plugin) may require manual inclusion of assets (CSS/JS) for proper rendering. The MkDocs plugin handles this automatically.
- gotcha If `pymdownx.superfences` is not enabled in your Markdown extensions configuration, `markdown-exec` will error out early. This is a common oversight when setting up the library.
- gotcha Output escaping for strings printed directly was improved in versions 1.10.2 and 1.10.3 to address display issues and potential vulnerabilities. Older versions might render unescaped output.
- gotcha When using `markdown-exec` with `Material for MkDocs` and `source='tabbed-left'` (or `tabbed-right`), code annotations placed immediately after the code block may break due to the generated tab structure. The annotation logic in Material for MkDocs expects the list to be directly after the code block.
Install
-
pip install markdown-exec -
pip install "markdown-exec[ansi]"
Imports
- formatter, validator
from markdown_exec import formatter, validator
Quickstart
import os
# mkdocs.yml configuration example
# plugins:
# - search
# - markdown-exec
# markdown_extensions:
# - pymdownx.superfences
# Example Markdown content (e.g., in docs/index.md)
markdown_content = '''
# My Executable Documentation
This is a simple example of markdown-exec in action.
```python exec="on"
import sys
print(f"Hello from Python {sys.version.split(' ')}!")
```
'''
# To simulate execution without a full MkDocs setup, one would typically process this
# via the Markdown library with the markdown-exec extension enabled.
# However, the primary intended use is within MkDocs.
# For a true quickstart, an MkDocs project is implicitly assumed.
# This example is illustrative of the Markdown content.
# To make it runnable for an agent, assume an MkDocs build process:
# 1. Create a dummy mkdocs.yml (if not present)
# 2. Create a dummy docs/index.md with the content above
# 3. Run `mkdocs build` or `mkdocs serve`
# This Python snippet shows how the markdown content looks, not how to run it directly in Python for output capture.
# The actual execution happens via the Markdown extension or MkDocs plugin.