Skip to content

Commit 862e693

Browse files
authored
Merge pull request #10532 from anntzer/py3pgf
Py3fy backend_pgf.
2 parents 2898bfa + 879b2e9 commit 862e693

File tree

6 files changed

+35
-45
lines changed

6 files changed

+35
-45
lines changed

doc/api/next_api_changes/2018-02-15-AL-deprecations.rst

+3
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,6 @@ The following functions and classes are deprecated:
1313
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead),
1414
- ``mathtext.unichr_safe`` (use ``chr`` instead),
1515
- ``texmanager.dvipng_hack_alpha``,
16+
17+
The following rcParams are deprecated:
18+
- ``pgf.debug`` (the pgf backend relies on logging),

lib/matplotlib/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,7 @@ def gen_candidates():
812812

813813
_deprecated_ignore_map = {'nbagg.transparent': 'figure.facecolor'}
814814

815-
_obsolete_set = {'plugins.directory', 'text.dvipnghack'}
815+
_obsolete_set = {'pgf.debug', 'plugins.directory', 'text.dvipnghack'}
816816

817817
# The following may use a value of None to suppress the warning.
818818
# do NOT include in _all_deprecated

lib/matplotlib/backends/backend_pgf.py

+30-40
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
from __future__ import (absolute_import, division, print_function,
2-
unicode_literals)
3-
4-
import six
5-
61
import atexit
72
import codecs
83
import errno
4+
import logging
95
import math
106
import os
117
import re
@@ -27,6 +23,8 @@
2723
from matplotlib.figure import Figure
2824
from matplotlib._pylab_helpers import Gcf
2925

26+
_log = logging.getLogger(__name__)
27+
3028

3129
###############################################################################
3230

@@ -193,10 +191,9 @@ def make_pdf_to_png_converter():
193191
tools_available = []
194192
# check for pdftocairo
195193
try:
196-
subprocess.check_output(
197-
["pdftocairo", "-v"], stderr=subprocess.STDOUT)
194+
subprocess.check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT)
198195
tools_available.append("pdftocairo")
199-
except:
196+
except OSError:
200197
pass
201198
# check for ghostscript
202199
gs, ver = mpl.checkdep_ghostscript()
@@ -212,7 +209,7 @@ def cairo_convert(pdffile, pngfile, dpi):
212209
return cairo_convert
213210
elif "gs" in tools_available:
214211
def gs_convert(pdffile, pngfile, dpi):
215-
cmd = [str(gs),
212+
cmd = [gs,
216213
'-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
217214
'-dUseCIEColor', '-dTextAlphaBits=4',
218215
'-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
@@ -226,11 +223,11 @@ def gs_convert(pdffile, pngfile, dpi):
226223

227224
class LatexError(Exception):
228225
def __init__(self, message, latex_output=""):
229-
Exception.__init__(self, message)
226+
super().__init__(message)
230227
self.latex_output = latex_output
231228

232229

233-
class LatexManagerFactory(object):
230+
class LatexManagerFactory:
234231
previous_instance = None
235232

236233
@staticmethod
@@ -242,18 +239,16 @@ def get_latex_manager():
242239
# Check if the previous instance of LatexManager can be reused.
243240
if (prev and prev.latex_header == latex_header
244241
and prev.texcommand == texcommand):
245-
if rcParams["pgf.debug"]:
246-
print("reusing LatexManager")
242+
_log.debug("reusing LatexManager")
247243
return prev
248244
else:
249-
if rcParams["pgf.debug"]:
250-
print("creating LatexManager")
245+
_log.debug("creating LatexManager")
251246
new_inst = LatexManager()
252247
LatexManagerFactory.previous_instance = new_inst
253248
return new_inst
254249

255250

256-
class LatexManager(object):
251+
class LatexManager:
257252
"""
258253
The LatexManager opens an instance of the LaTeX application for
259254
determining the metrics of text elements. The LaTeX environment can be
@@ -306,7 +301,6 @@ def __init__(self):
306301
# store references for __del__
307302
self._os_path = os.path
308303
self._shutil = shutil
309-
self._debug = rcParams["pgf.debug"]
310304

311305
# create a tmp directory for running latex, remember to cleanup
312306
self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
@@ -317,26 +311,24 @@ def __init__(self):
317311
self.latex_header = LatexManager._build_latex_header()
318312
latex_end = "\n\\makeatletter\n\\@@end\n"
319313
try:
320-
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
314+
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
321315
stdin=subprocess.PIPE,
322316
stdout=subprocess.PIPE,
323317
cwd=self.tmpdir)
324-
except OSError as e:
325-
if e.errno == errno.ENOENT:
326-
raise RuntimeError(
327-
"Latex command not found. Install %r or change "
328-
"pgf.texsystem to the desired command." % self.texcommand)
329-
else:
330-
raise RuntimeError(
331-
"Error starting process %r" % self.texcommand)
318+
except FileNotFoundError:
319+
raise RuntimeError(
320+
"Latex command not found. Install %r or change "
321+
"pgf.texsystem to the desired command." % self.texcommand)
322+
except OSError:
323+
raise RuntimeError("Error starting process %r" % self.texcommand)
332324
test_input = self.latex_header + latex_end
333325
stdout, stderr = latex.communicate(test_input.encode("utf-8"))
334326
if latex.returncode != 0:
335327
raise LatexError("LaTeX returned an error, probably missing font "
336328
"or error in preamble:\n%s" % stdout)
337329

338330
# open LaTeX process for real work
339-
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
331+
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
340332
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
341333
cwd=self.tmpdir)
342334
self.latex = latex
@@ -366,8 +358,7 @@ def _cleanup(self):
366358
sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
367359

368360
def __del__(self):
369-
if self._debug:
370-
print("deleting LatexManager")
361+
_log.debug("deleting LatexManager")
371362
self._cleanup()
372363

373364
def get_width_height_descent(self, text, prop):
@@ -787,7 +778,7 @@ class GraphicsContextPgf(GraphicsContextBase):
787778
########################################################################
788779

789780

790-
class TmpDirCleaner(object):
781+
class TmpDirCleaner:
791782
remaining_tmpdirs = set()
792783

793784
@staticmethod
@@ -797,10 +788,10 @@ def add(tmpdir):
797788
@staticmethod
798789
def cleanup_remaining_tmpdirs():
799790
for tmpdir in TmpDirCleaner.remaining_tmpdirs:
800-
try:
801-
shutil.rmtree(tmpdir)
802-
except:
803-
sys.stderr.write("error deleting tmp directory %s\n" % tmpdir)
791+
shutil.rmtree(
792+
tmpdir,
793+
onerror=lambda *args: print("error deleting tmp directory %s"
794+
% tmpdir, file=sys.stderr))
804795

805796

806797
class FigureCanvasPgf(FigureCanvasBase):
@@ -879,7 +870,7 @@ def print_pgf(self, fname_or_fh, *args, **kwargs):
879870
return
880871

881872
# figure out where the pgf is to be written to
882-
if isinstance(fname_or_fh, six.string_types):
873+
if isinstance(fname_or_fh, str):
883874
with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh:
884875
self._print_pgf_to_fh(fh, *args, **kwargs)
885876
elif is_writable_file_like(fname_or_fh):
@@ -918,7 +909,7 @@ def _print_pdf_to_fh(self, fh, *args, **kwargs):
918909
fh_tex.write(latexcode)
919910

920911
texcommand = get_texcommand()
921-
cmdargs = [str(texcommand), "-interaction=nonstopmode",
912+
cmdargs = [texcommand, "-interaction=nonstopmode",
922913
"-halt-on-error", "figure.tex"]
923914
try:
924915
subprocess.check_output(
@@ -946,7 +937,7 @@ def print_pdf(self, fname_or_fh, *args, **kwargs):
946937
return
947938

948939
# figure out where the pdf is to be written to
949-
if isinstance(fname_or_fh, six.string_types):
940+
if isinstance(fname_or_fh, str):
950941
with open(fname_or_fh, "wb") as fh:
951942
self._print_pdf_to_fh(fh, *args, **kwargs)
952943
elif is_writable_file_like(fname_or_fh):
@@ -982,7 +973,7 @@ def print_png(self, fname_or_fh, *args, **kwargs):
982973
self._print_pgf_to_fh(None, *args, **kwargs)
983974
return
984975

985-
if isinstance(fname_or_fh, six.string_types):
976+
if isinstance(fname_or_fh, str):
986977
with open(fname_or_fh, "wb") as fh:
987978
self._print_png_to_fh(fh, *args, **kwargs)
988979
elif is_writable_file_like(fname_or_fh):
@@ -995,8 +986,7 @@ def get_renderer(self):
995986

996987

997988
class FigureManagerPgf(FigureManagerBase):
998-
def __init__(self, *args):
999-
FigureManagerBase.__init__(self, *args)
989+
pass
1000990

1001991

1002992
@_Backend.export

lib/matplotlib/mpl-data/stylelib/_classic_test.mplstyle

-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,6 @@ pdf.inheritcolor : False
441441
pdf.use14corefonts : False
442442

443443
# pgf backend params
444-
pgf.debug : False
445444
pgf.texsystem : xelatex
446445
pgf.rcfonts : True
447446
pgf.preamble :

lib/matplotlib/mpl-data/stylelib/classic.mplstyle

-1
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,6 @@ pdf.inheritcolor : False
443443
pdf.use14corefonts : False
444444

445445
# pgf backend params
446-
pgf.debug : False
447446
pgf.texsystem : xelatex
448447
pgf.rcfonts : True
449448
pgf.preamble :

matplotlibrc.template

+1-2
Original file line numberDiff line numberDiff line change
@@ -565,9 +565,8 @@ backend : $TEMPLATE_BACKEND
565565
## instead of uuid4
566566
### pgf parameter
567567
#pgf.rcfonts : True
568-
#pgf.preamble :
568+
#pgf.preamble :
569569
#pgf.texsystem : xelatex
570-
#pgf.debug : False
571570

572571
### docstring params
573572
##docstring.hardcopy = False ## set this when you want to generate hardcopy docstring

0 commit comments

Comments
 (0)