0
# Sphinx-Gallery
1
2
A Sphinx extension that automatically builds HTML galleries from collections of Python example scripts, enabling developers to create comprehensive documentation with executable code examples, output displays, and downloadable formats. Sphinx-Gallery provides advanced features including automatic execution of example scripts with output capture, thumbnail generation from matplotlib plots, cross-referencing capabilities, Jupyter notebook conversion, and integration with various visualization libraries.
3
4
## Package Information
5
6
- **Package Name**: sphinx-gallery
7
- **Language**: Python
8
- **Installation**: `pip install sphinx-gallery`
9
- **Version**: 0.19.0
10
11
## Core Imports
12
13
```python
14
import sphinx_gallery
15
```
16
17
For extension setup in Sphinx `conf.py`:
18
19
```python
20
extensions = ['sphinx_gallery.gen_gallery']
21
```
22
23
For alternative CSS-only setup:
24
25
```python
26
extensions = ['sphinx_gallery.load_style']
27
```
28
29
## Basic Usage
30
31
### Setting up Sphinx-Gallery in conf.py
32
33
```python
34
# conf.py
35
extensions = ['sphinx_gallery.gen_gallery']
36
37
sphinx_gallery_conf = {
38
'examples_dirs': '../examples', # Source directory for examples
39
'gallery_dirs': 'auto_examples', # Output directory for generated gallery
40
}
41
```
42
43
### Using RST Directives
44
45
In your RST documentation files:
46
47
```rst
48
.. minigallery:: numpy.mean
49
:add-heading: Examples using ``numpy.mean``
50
51
.. image-sg:: /auto_examples/images/plot_example_001.png
52
:alt: Example plot
53
:srcset: /auto_examples/images/plot_example_001.png, /auto_examples/images/plot_example_001_2x.png 2x
54
```
55
56
### Converting Python Scripts to Jupyter Notebooks
57
58
Command line usage:
59
60
```bash
61
sphinx_gallery_py2jupyter my_example.py
62
```
63
64
Programmatic usage:
65
66
```python
67
from sphinx_gallery.notebook import python_to_jupyter
68
69
python_to_jupyter(
70
'my_example.py',
71
'output_notebook.ipynb',
72
gallery_conf,
73
target_dir
74
)
75
```
76
77
## Architecture
78
79
Sphinx-Gallery follows a modular architecture with several key components:
80
81
- **Extension Core**: Main setup and configuration handling in `gen_gallery` module
82
- **Directives**: Custom RST directives for enhanced documentation features
83
- **Scrapers**: Image extraction system supporting matplotlib and custom scrapers
84
- **Generation Pipeline**: Automated RST and HTML generation from Python scripts
85
- **Notebook Integration**: Bidirectional conversion between Python scripts and Jupyter notebooks
86
87
The extension integrates deeply with Sphinx's event system and provides hooks for customization at every stage of the gallery generation process.
88
89
## Capabilities
90
91
### Extension Setup
92
93
Core extension configuration and setup functions for integrating Sphinx-Gallery into Sphinx documentation projects.
94
95
```python { .api }
96
def setup(app):
97
"""
98
Main Sphinx extension setup function.
99
100
Parameters:
101
- app: Sphinx application object
102
103
Returns:
104
dict: Extension metadata
105
"""
106
```
107
108
[Extension Setup](./extension-setup.md)
109
110
### RST Directives
111
112
Custom RST directives for creating mini-galleries and enhanced image displays in documentation.
113
114
```python { .api }
115
class MiniGallery:
116
"""RST directive for creating mini-galleries of related examples."""
117
118
class ImageSg:
119
"""Enhanced image directive with responsive srcset support."""
120
```
121
122
[RST Directives](./directives.md)
123
124
### Image Scrapers
125
126
System for extracting and processing images from executed Python code, with built-in matplotlib support and extensible architecture.
127
128
```python { .api }
129
def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
130
"""
131
Scrapes matplotlib figures from code execution.
132
133
Parameters:
134
- block: dict, code block information
135
- block_vars: dict, execution variables
136
- gallery_conf: dict, gallery configuration
137
138
Returns:
139
list: Image filenames that were saved
140
"""
141
```
142
143
[Image Scrapers](./scrapers.md)
144
145
### Gallery Sorting
146
147
Flexible sorting system for organizing galleries and examples within galleries.
148
149
```python { .api }
150
class ExplicitOrder:
151
"""Sorting key for explicit ordering of gallery subsections."""
152
153
def __init__(self, ordered_list):
154
"""
155
Parameters:
156
- ordered_list: list, explicit order of items
157
"""
158
```
159
160
[Gallery Sorting](./sorting.md)
161
162
### Jupyter Notebook Support
163
164
Conversion tools and command-line interface for working with Jupyter notebooks.
165
166
```python { .api }
167
def python_to_jupyter_cli(args=None, namespace=None, sphinx_gallery_conf=None):
168
"""
169
Command-line interface for converting Python scripts to Jupyter notebooks.
170
171
Parameters:
172
- args: list, command line arguments
173
- namespace: Namespace, parsed arguments
174
- sphinx_gallery_conf: dict, gallery configuration
175
"""
176
```
177
178
[Jupyter Notebook Support](./notebooks.md)
179
180
### Utilities
181
182
Helper functions for image processing, file operations, and common tasks.
183
184
```python { .api }
185
def scale_image(in_fname, out_fname, max_width, max_height):
186
"""
187
Scales images while maintaining aspect ratio.
188
189
Parameters:
190
- in_fname: str, input filename
191
- out_fname: str, output filename
192
- max_width: int, maximum width in pixels
193
- max_height: int, maximum height in pixels
194
"""
195
```
196
197
[Utilities](./utilities.md)
198
199
## Configuration System
200
201
Sphinx-Gallery is configured through the `sphinx_gallery_conf` dictionary in your Sphinx `conf.py` file. Key configuration categories include:
202
203
### Core Gallery Settings
204
- **examples_dirs**: Source directories containing example scripts
205
- **gallery_dirs**: Output directories for generated galleries
206
- **filename_pattern**: Regex pattern for identifying example files
207
- **plot_gallery**: Whether to execute examples during build
208
209
### Execution Control
210
- **abort_on_example_error**: Stop build on first error
211
- **expected_failing_examples**: List of scripts expected to fail
212
- **run_stale_examples**: Re-run examples when source changes
213
214
### Output Options
215
- **download_all_examples**: Generate download links for examples
216
- **thumbnail_size**: Dimensions for generated thumbnails
217
- **show_memory**: Display memory usage information
218
- **show_signature**: Include Sphinx-Gallery signature in output
219
220
### Advanced Configuration
221
- **image_scrapers**: List of functions for extracting images
222
- **reset_modules**: Modules to reset between example executions
223
- **subsection_order**: Function for ordering gallery subsections
224
- **within_subsection_order**: Function for ordering within subsections
225
226
## Package Metadata
227
228
```python { .api }
229
__version__ = "0.19.0"
230
231
def glr_path_static():
232
"""
233
Returns path to packaged static files.
234
235
Returns:
236
str: Absolute path to _static directory
237
"""
238
```
239
240
The package provides access to version information and static assets (CSS, JavaScript) for custom integrations.