如何在Python代码文件中嵌入图片并生成Markdown/HTML文档?
Absolutely! Both mkDocs and Sphinx support extracting documentation (including images) directly from your Python files—no separate .md/.rst docs required. Plus, there are lightweight tools like pdoc that make this even simpler. Here's how to implement each approach:
Using Sphinx
Sphinx is the go-to for Python documentation, and it’s fully capable of pulling image references from your code’s docstrings.
Option 1: Reference Local Image Files
If you don’t mind keeping image files alongside your .py files (but still no separate doc files), you can link to them using either reStructuredText or MyST Markdown (Sphinx’s Markdown flavor):
Example with reStructuredText Docstrings:
def process_data(): """ Turns raw input into structured, usable data. .. image:: ../images/data_flow.png :alt: Diagram showing data from input to processed output :width: 600px """ # Your code logic here
Example with MyST Markdown (for Markdown fans):
First, enable the MyST parser in your Sphinx conf.py:
extensions = ["myst_parser", "sphinx.ext.autodoc"]
Then add Markdown image syntax to your Python docstring:
def visualize_results(): """ Creates interactive plots from processed data. {: width="600"} """ # Your visualization code here
Option 2: Inline Base64 Images (No External Files)
If you want everything contained within the .py file (no separate image files), encode your image to base64 and embed it directly in the docstring. This keeps your project self-contained but will make your .py file larger:
def generate_summary(): """ Produces a high-level summary of the analysis. .. image:: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5gMVESkqQzk0NAAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAAUSURBVDjLY2AAAUaGQAAE2gAADeAH31nW5gAAAABJRU5ErkJggg== :alt: Mini preview of the summary report """ # Your summary code here
Run sphinx-build as usual, and Sphinx will render the images directly from your docstrings into HTML.
Using mkDocs
mkDocs is perfect if you prefer Markdown-based docs, and the mkdocstrings plugin lets you pull docs straight from your Python files.
Step 1: Set Up mkdocstrings
Install the plugin first:
pip install mkdocstrings[python]
Add it to your mkdocs.yml:
plugins: - mkdocstrings
Step 2: Add Images to Python Docstrings
Use standard Markdown image syntax in your docstrings—either linking to local files or embedding base64:
Local Image Example:
def train_model(): """ Trains a classification model on the labeled dataset. {: width="600"} """ # Your training code here
Inline Base64 Example:
def evaluate_model(): """ Tests model performance against unseen test data.  """ # Your evaluation code here
Step 3: Generate Docs
Run mkdocs build to create static HTML docs, or mkdocs serve to preview your site live. The plugin will extract your docstrings (including images) and render them seamlessly.
Lightweight Alternative: pdoc
If you want a no-fuss tool that generates HTML directly from your Python files without extra configuration, try pdoc:
- Install it:
pip install pdoc - Generate docs:
pdoc your_script.py -o docs
pdoc supports Markdown in docstrings, so you can include image references (local or base64) just like in the mkDocs examples. It will render the images in the generated HTML automatically.
Quick Tips:
- Base64 embedding keeps everything self-contained but increases .py file size—use it sparingly for small images.
- For local images, keep them in a directory relative to your .py files so the tools can locate them during rendering.
- Both Sphinx and mkDocs can export to other formats (like PDF) if needed, though that requires additional setup.
内容的提问来源于stack exchange,提问作者guilhermecgs

