Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 432f5a6

Browse files
committed
NF+BF: add close-figs option to plot_directive
Add `close-figs` choice to `context` option of plot_directive. This keeps the current context, but closes any previous figures. This is necessary because the plot directive first runs the specified code, then collects figures with: fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() If you are using the "context" option, prior figures maybe generated from a previous plot directive command, are still open, and therefore collected with the new figure(s). The old figures will usually be earlier in the list, and so, for something like this ReST block, you will always get the first generated figure (``range(10)``) repeated in the second plot directive panel: ####### A title ####### .. plot:: :context: import matplotlib.pyplot as plt plt.plot(range(10)) Then some text. .. plot:: :context: plt.figure() plt.plot(range(5), 'r') This PR add a context option of form `:context: close-figs` that closes any previous figure windows before running the directive code. It also adds a small test sphinx project to test the directive commands. See email discussion thread starting here: https://www.mail-archive.com/[email protected]/msg10816.html
1 parent edd4f86 commit 432f5a6

File tree

8 files changed

+484
-0
lines changed

8 files changed

+484
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Make tests a package
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
""" Tests for tinypages build using sphinx extensions """
2+
3+
import shutil
4+
import tempfile
5+
6+
from os.path import (join as pjoin, dirname, isdir)
7+
8+
from subprocess import call, Popen, PIPE
9+
10+
from nose import SkipTest
11+
from nose.tools import assert_true
12+
13+
HERE = dirname(__file__)
14+
TINY_PAGES = pjoin(HERE, 'tinypages')
15+
16+
17+
def setup():
18+
# Check we have the sphinx-build command
19+
try:
20+
ret = call(['sphinx-build', '--help'], stdout=PIPE, stderr=PIPE)
21+
except OSError:
22+
raise SkipTest('Need sphinx-build on path for these tests')
23+
if ret != 0:
24+
raise RuntimeError('sphinx-build does not return 0')
25+
26+
27+
def file_same(file1, file2):
28+
with open(file1, 'rb') as fobj:
29+
contents1 = fobj.read()
30+
with open(file2, 'rb') as fobj:
31+
contents2 = fobj.read()
32+
return contents1 == contents2
33+
34+
35+
class TestTinyPages(object):
36+
# Test build and output of tinypages project
37+
38+
@classmethod
39+
def setup_class(cls):
40+
cls.page_build = tempfile.mkdtemp()
41+
try:
42+
cls.html_dir = pjoin(cls.page_build, 'html')
43+
cls.doctree_dir = pjoin(cls.page_build, 'doctrees')
44+
# Build the pages with warnings turned into errors
45+
cmd = ['sphinx-build', '-W', '-b', 'html',
46+
'-d', cls.doctree_dir,
47+
TINY_PAGES,
48+
cls.html_dir]
49+
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
50+
out, err = proc.communicate()
51+
except Exception as e:
52+
shutil.rmtree(cls.page_build)
53+
raise e
54+
if proc.returncode != 0:
55+
shutil.rmtree(cls.page_build)
56+
raise RuntimeError('sphinx-build failed with stdout:\n'
57+
'{0}\nstderr:\n{1}\n'.format(
58+
out, err))
59+
60+
@classmethod
61+
def teardown_class(cls):
62+
shutil.rmtree(cls.page_build)
63+
64+
def test_some_plots(self):
65+
assert_true(isdir(self.html_dir))
66+
def plot_file(num):
67+
return pjoin(self.html_dir, 'some_plots-{0}.png'.format(num))
68+
range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)]
69+
# Plot 5 is range(6) plot
70+
assert_true(file_same(range_6, plot_file(5)))
71+
# Plot 7 is range(4) plot
72+
assert_true(file_same(range_4, plot_file(7)))
73+
# Plot 11 is range(10) plot
74+
assert_true(file_same(range_10, plot_file(11)))
75+
# Plot 12 uses the old range(10) figure and the new range(6) figure
76+
assert_true(file_same(range_10, plot_file('12_00')))
77+
assert_true(file_same(range_6, plot_file('12_01')))
78+
# Plot 13 shows close-figs in action
79+
assert_true(file_same(range_4, plot_file(13)))
80+
# Plot 14 has included source
81+
with open(pjoin(self.html_dir, 'some_plots.html'), 'rt') as fobj:
82+
html_contents = fobj.read()
83+
assert_true('# Only a comment' in html_contents)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
_build/
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Test project for matplotlib sphinx extensions
2+
3+
A tiny sphinx project from ``sphinx-quickstart`` with all default answers.

lib/matplotlib/sphinxext/tests/tinypages/_static/.gitignore

Whitespace-only changes.
Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# tinypages documentation build configuration file, created by
4+
# sphinx-quickstart on Tue Mar 18 11:58:34 2014.
5+
#
6+
# This file is execfile()d with the current directory set to its
7+
# containing dir.
8+
#
9+
# Note that not all possible configuration values are present in this
10+
# autogenerated file.
11+
#
12+
# All configuration values have a default; values that are commented out
13+
# serve to show the default.
14+
15+
import sys
16+
from os.path import join as pjoin, abspath
17+
18+
# If extensions (or modules to document with autodoc) are in another directory,
19+
# add these directories to sys.path here. If the directory is relative to the
20+
# documentation root, use os.path.abspath to make it absolute, like shown here.
21+
#sys.path.insert(0, os.path.abspath('.'))
22+
sys.path.insert(0, abspath(pjoin('..', '..')))
23+
24+
# -- General configuration ------------------------------------------------
25+
26+
# If your documentation needs a minimal Sphinx version, state it here.
27+
#needs_sphinx = '1.0'
28+
29+
# Add any Sphinx extension module names here, as strings. They can be
30+
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
31+
# ones.
32+
extensions = ['matplotlib.sphinxext.plot_directive']
33+
34+
# Add any paths that contain templates here, relative to this directory.
35+
templates_path = ['_templates']
36+
37+
# The suffix of source filenames.
38+
source_suffix = '.rst'
39+
40+
# The encoding of source files.
41+
#source_encoding = 'utf-8-sig'
42+
43+
# The master toctree document.
44+
master_doc = 'index'
45+
46+
# General information about the project.
47+
project = u'tinypages'
48+
copyright = u'2014, Matplotlib developers'
49+
50+
# The version info for the project you're documenting, acts as replacement for
51+
# |version| and |release|, also used in various other places throughout the
52+
# built documents.
53+
#
54+
# The short X.Y version.
55+
version = '0.1'
56+
# The full version, including alpha/beta/rc tags.
57+
release = '0.1'
58+
59+
# The language for content autogenerated by Sphinx. Refer to documentation
60+
# for a list of supported languages.
61+
#language = None
62+
63+
# There are two options for replacing |today|: either, you set today to some
64+
# non-false value, then it is used:
65+
#today = ''
66+
# Else, today_fmt is used as the format for a strftime call.
67+
#today_fmt = '%B %d, %Y'
68+
69+
# List of patterns, relative to source directory, that match files and
70+
# directories to ignore when looking for source files.
71+
exclude_patterns = ['_build']
72+
73+
# The reST default role (used for this markup: `text`) to use for all
74+
# documents.
75+
#default_role = None
76+
77+
# If true, '()' will be appended to :func: etc. cross-reference text.
78+
#add_function_parentheses = True
79+
80+
# If true, the current module name will be prepended to all description
81+
# unit titles (such as .. function::).
82+
#add_module_names = True
83+
84+
# If true, sectionauthor and moduleauthor directives will be shown in the
85+
# output. They are ignored by default.
86+
#show_authors = False
87+
88+
# The name of the Pygments (syntax highlighting) style to use.
89+
pygments_style = 'sphinx'
90+
91+
# A list of ignored prefixes for module index sorting.
92+
#modindex_common_prefix = []
93+
94+
# If true, keep warnings as "system message" paragraphs in the built documents.
95+
#keep_warnings = False
96+
97+
98+
# -- Options for HTML output ----------------------------------------------
99+
100+
# The theme to use for HTML and HTML Help pages. See the documentation for
101+
# a list of builtin themes.
102+
html_theme = 'default'
103+
104+
# Theme options are theme-specific and customize the look and feel of a theme
105+
# further. For a list of options available for each theme, see the
106+
# documentation.
107+
#html_theme_options = {}
108+
109+
# Add any paths that contain custom themes here, relative to this directory.
110+
#html_theme_path = []
111+
112+
# The name for this set of Sphinx documents. If None, it defaults to
113+
# "<project> v<release> documentation".
114+
#html_title = None
115+
116+
# A shorter title for the navigation bar. Default is the same as html_title.
117+
#html_short_title = None
118+
119+
# The name of an image file (relative to this directory) to place at the top
120+
# of the sidebar.
121+
#html_logo = None
122+
123+
# The name of an image file (within the static path) to use as favicon of the
124+
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
125+
# pixels large.
126+
#html_favicon = None
127+
128+
# Add any paths that contain custom static files (such as style sheets) here,
129+
# relative to this directory. They are copied after the builtin static files,
130+
# so a file named "default.css" will overwrite the builtin "default.css".
131+
html_static_path = ['_static']
132+
133+
# Add any extra paths that contain custom files (such as robots.txt or
134+
# .htaccess) here, relative to this directory. These files are copied
135+
# directly to the root of the documentation.
136+
#html_extra_path = []
137+
138+
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
139+
# using the given strftime format.
140+
#html_last_updated_fmt = '%b %d, %Y'
141+
142+
# If true, SmartyPants will be used to convert quotes and dashes to
143+
# typographically correct entities.
144+
#html_use_smartypants = True
145+
146+
# Custom sidebar templates, maps document names to template names.
147+
#html_sidebars = {}
148+
149+
# Additional templates that should be rendered to pages, maps page names to
150+
# template names.
151+
#html_additional_pages = {}
152+
153+
# If false, no module index is generated.
154+
#html_domain_indices = True
155+
156+
# If false, no index is generated.
157+
#html_use_index = True
158+
159+
# If true, the index is split into individual pages for each letter.
160+
#html_split_index = False
161+
162+
# If true, links to the reST sources are added to the pages.
163+
#html_show_sourcelink = True
164+
165+
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
166+
#html_show_sphinx = True
167+
168+
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
169+
#html_show_copyright = True
170+
171+
# If true, an OpenSearch description file will be output, and all pages will
172+
# contain a <link> tag referring to it. The value of this option must be the
173+
# base URL from which the finished HTML is served.
174+
#html_use_opensearch = ''
175+
176+
# This is the file name suffix for HTML files (e.g. ".xhtml").
177+
#html_file_suffix = None
178+
179+
# Output file base name for HTML help builder.
180+
htmlhelp_basename = 'tinypagesdoc'
181+
182+
183+
# -- Options for LaTeX output ---------------------------------------------
184+
185+
latex_elements = {
186+
# The paper size ('letterpaper' or 'a4paper').
187+
#'papersize': 'letterpaper',
188+
189+
# The font size ('10pt', '11pt' or '12pt').
190+
#'pointsize': '10pt',
191+
192+
# Additional stuff for the LaTeX preamble.
193+
#'preamble': '',
194+
}
195+
196+
# Grouping the document tree into LaTeX files. List of tuples
197+
# (source start file, target name, title,
198+
# author, documentclass [howto, manual, or own class]).
199+
latex_documents = [
200+
('index', 'tinypages.tex', u'tinypages Documentation',
201+
u'Matplotlib developers', 'manual'),
202+
]
203+
204+
# The name of an image file (relative to this directory) to place at the top of
205+
# the title page.
206+
#latex_logo = None
207+
208+
# For "manual" documents, if this is true, then toplevel headings are parts,
209+
# not chapters.
210+
#latex_use_parts = False
211+
212+
# If true, show page references after internal links.
213+
#latex_show_pagerefs = False
214+
215+
# If true, show URL addresses after external links.
216+
#latex_show_urls = False
217+
218+
# Documents to append as an appendix to all manuals.
219+
#latex_appendices = []
220+
221+
# If false, no module index is generated.
222+
#latex_domain_indices = True
223+
224+
225+
# -- Options for manual page output ---------------------------------------
226+
227+
# One entry per manual page. List of tuples
228+
# (source start file, name, description, authors, manual section).
229+
man_pages = [
230+
('index', 'tinypages', u'tinypages Documentation',
231+
[u'Matplotlib developers'], 1)
232+
]
233+
234+
# If true, show URL addresses after external links.
235+
#man_show_urls = False
236+
237+
238+
# -- Options for Texinfo output -------------------------------------------
239+
240+
# Grouping the document tree into Texinfo files. List of tuples
241+
# (source start file, target name, title, author,
242+
# dir menu entry, description, category)
243+
texinfo_documents = [
244+
('index', 'tinypages', u'tinypages Documentation',
245+
u'Matplotlib developers', 'tinypages', 'One line description of project.',
246+
'Miscellaneous'),
247+
]
248+
249+
# Documents to append as an appendix to all manuals.
250+
#texinfo_appendices = []
251+
252+
# If false, no module index is generated.
253+
#texinfo_domain_indices = True
254+
255+
# How to display URL addresses: 'footnote', 'no', or 'inline'.
256+
#texinfo_show_urls = 'footnote'
257+
258+
# If true, do not generate a @detailmenu in the "Top" node's menu.
259+
#texinfo_no_detailmenu = False
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
.. tinypages documentation master file, created by
2+
sphinx-quickstart on Tue Mar 18 11:58:34 2014.
3+
You can adapt this file completely to your liking, but it should at least
4+
contain the root `toctree` directive.
5+
6+
Welcome to tinypages's documentation!
7+
=====================================
8+
9+
Contents:
10+
11+
.. toctree::
12+
:maxdepth: 2
13+
14+
some_plots
15+
16+
Indices and tables
17+
==================
18+
19+
* :ref:`genindex`
20+
* :ref:`modindex`
21+
* :ref:`search`

0 commit comments

Comments
 (0)