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

Skip to content

Commit 24a2959

Browse files
committed
Py3fy backend_pgf.
1 parent a94f839 commit 24a2959

File tree

3 files changed

+42
-47
lines changed

3 files changed

+42
-47
lines changed
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
Deprecations
22
````````````
33
The following functions are deprecated:
4-
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead)
5-
- ``mathtext.unichr_safe`` (use ``chr`` instead)
4+
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead),
5+
- ``mathtext.unichr_safe`` (use ``chr`` instead).
6+
7+
The following rcParams are deprecated:
8+
- ``pgf.debug`` (the pgf backend relies on logging).

lib/matplotlib/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -855,7 +855,7 @@ def gen_candidates():
855855

856856
_deprecated_ignore_map = {'nbagg.transparent': 'figure.facecolor'}
857857

858-
_obsolete_set = {'plugins.directory', 'text.dvipnghack'}
858+
_obsolete_set = {'pgf.debug', 'plugins.directory', 'text.dvipnghack'}
859859

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

lib/matplotlib/backends/backend_pgf.py

Lines changed: 36 additions & 44 deletions
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
@@ -23,9 +19,10 @@
2319
from matplotlib.backends.backend_mixed import MixedModeRenderer
2420
from matplotlib.cbook import is_writable_file_like
2521
from matplotlib.compat import subprocess
26-
from matplotlib.compat.subprocess import check_output
2722
from matplotlib.path import Path
2823

24+
_log = logging.getLogger(__name__)
25+
2926

3027
###############################################################################
3128

@@ -42,7 +39,8 @@
4239
# assuming fontconfig is installed and the command 'fc-list' exists
4340
try:
4441
# list scalable (non-bitmap) fonts
45-
fc_list = check_output([str('fc-list'), ':outline,scalable', 'family'])
42+
fc_list = subprocess.check_output(
43+
['fc-list', ':outline,scalable', 'family'])
4644
fc_list = fc_list.decode('utf8')
4745
system_fonts = [f.split(',')[0] for f in fc_list.splitlines()]
4846
system_fonts = list(set(system_fonts))
@@ -173,7 +171,7 @@ def make_pdf_to_png_converter():
173171
tools_available = []
174172
# check for pdftocairo
175173
try:
176-
check_output([str("pdftocairo"), "-v"], stderr=subprocess.STDOUT)
174+
subprocess.check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT)
177175
tools_available.append("pdftocairo")
178176
except:
179177
pass
@@ -185,31 +183,31 @@ def make_pdf_to_png_converter():
185183
# pick converter
186184
if "pdftocairo" in tools_available:
187185
def cairo_convert(pdffile, pngfile, dpi):
188-
cmd = [str("pdftocairo"), "-singlefile", "-png", "-r", "%d" % dpi,
186+
cmd = ["pdftocairo", "-singlefile", "-png", "-r", "%d" % dpi,
189187
pdffile, os.path.splitext(pngfile)[0]]
190-
check_output(cmd, stderr=subprocess.STDOUT)
188+
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
191189
return cairo_convert
192190
elif "gs" in tools_available:
193191
def gs_convert(pdffile, pngfile, dpi):
194-
cmd = [str(gs),
192+
cmd = [gs,
195193
'-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
196194
'-dUseCIEColor', '-dTextAlphaBits=4',
197195
'-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
198196
'-sDEVICE=png16m', '-sOutputFile=%s' % pngfile,
199197
'-r%d' % dpi, pdffile]
200-
check_output(cmd, stderr=subprocess.STDOUT)
198+
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
201199
return gs_convert
202200
else:
203201
raise RuntimeError("No suitable pdf to png renderer found.")
204202

205203

206204
class LatexError(Exception):
207205
def __init__(self, message, latex_output=""):
208-
Exception.__init__(self, message)
206+
super().__init__(message)
209207
self.latex_output = latex_output
210208

211209

212-
class LatexManagerFactory(object):
210+
class LatexManagerFactoryobject:
213211
previous_instance = None
214212

215213
@staticmethod
@@ -221,18 +219,16 @@ def get_latex_manager():
221219
# Check if the previous instance of LatexManager can be reused.
222220
if (prev and prev.latex_header == latex_header
223221
and prev.texcommand == texcommand):
224-
if rcParams["pgf.debug"]:
225-
print("reusing LatexManager")
222+
_log.debug("reusing LatexManager")
226223
return prev
227224
else:
228-
if rcParams["pgf.debug"]:
229-
print("creating LatexManager")
225+
_log.debug("creating LatexManager")
230226
new_inst = LatexManager()
231227
LatexManagerFactory.previous_instance = new_inst
232228
return new_inst
233229

234230

235-
class LatexManager(object):
231+
class LatexManager:
236232
"""
237233
The LatexManager opens an instance of the LaTeX application for
238234
determining the metrics of text elements. The LaTeX environment can be
@@ -285,7 +281,6 @@ def __init__(self):
285281
# store references for __del__
286282
self._os_path = os.path
287283
self._shutil = shutil
288-
self._debug = rcParams["pgf.debug"]
289284

290285
# create a tmp directory for running latex, remember to cleanup
291286
self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
@@ -296,26 +291,24 @@ def __init__(self):
296291
self.latex_header = LatexManager._build_latex_header()
297292
latex_end = "\n\\makeatletter\n\\@@end\n"
298293
try:
299-
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
294+
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
300295
stdin=subprocess.PIPE,
301296
stdout=subprocess.PIPE,
302297
cwd=self.tmpdir)
303-
except OSError as e:
304-
if e.errno == errno.ENOENT:
305-
raise RuntimeError(
306-
"Latex command not found. Install %r or change "
307-
"pgf.texsystem to the desired command." % self.texcommand)
308-
else:
309-
raise RuntimeError(
310-
"Error starting process %r" % self.texcommand)
298+
except FileNotFoundError:
299+
raise RuntimeError(
300+
"Latex command not found. Install %r or change "
301+
"pgf.texsystem to the desired command." % self.texcommand)
302+
except OSError:
303+
raise RuntimeError("Error starting process %r" % self.texcommand)
311304
test_input = self.latex_header + latex_end
312305
stdout, stderr = latex.communicate(test_input.encode("utf-8"))
313306
if latex.returncode != 0:
314307
raise LatexError("LaTeX returned an error, probably missing font "
315308
"or error in preamble:\n%s" % stdout)
316309

317310
# open LaTeX process for real work
318-
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
311+
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
319312
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
320313
cwd=self.tmpdir)
321314
self.latex = latex
@@ -345,8 +338,7 @@ def _cleanup(self):
345338
sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
346339

347340
def __del__(self):
348-
if self._debug:
349-
print("deleting LatexManager")
341+
_log.debug("deleting LatexManager")
350342
self._cleanup()
351343

352344
def get_width_height_descent(self, text, prop):
@@ -766,7 +758,7 @@ class GraphicsContextPgf(GraphicsContextBase):
766758
########################################################################
767759

768760

769-
class TmpDirCleaner(object):
761+
class TmpDirCleaner:
770762
remaining_tmpdirs = set()
771763

772764
@staticmethod
@@ -776,10 +768,10 @@ def add(tmpdir):
776768
@staticmethod
777769
def cleanup_remaining_tmpdirs():
778770
for tmpdir in TmpDirCleaner.remaining_tmpdirs:
779-
try:
780-
shutil.rmtree(tmpdir)
781-
except:
782-
sys.stderr.write("error deleting tmp directory %s\n" % tmpdir)
771+
shutil.rmtree(
772+
tmpdir,
773+
onerror=lambda *args: print("error deleting tmp directory %s"
774+
% tmpdir, file=sys.stderr))
783775

784776

785777
class FigureCanvasPgf(FigureCanvasBase):
@@ -858,7 +850,7 @@ def print_pgf(self, fname_or_fh, *args, **kwargs):
858850
return
859851

860852
# figure out where the pgf is to be written to
861-
if isinstance(fname_or_fh, six.string_types):
853+
if isinstance(fname_or_fh, str):
862854
with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh:
863855
self._print_pgf_to_fh(fh, *args, **kwargs)
864856
elif is_writable_file_like(fname_or_fh):
@@ -897,10 +889,11 @@ def _print_pdf_to_fh(self, fh, *args, **kwargs):
897889
fh_tex.write(latexcode)
898890

899891
texcommand = get_texcommand()
900-
cmdargs = [str(texcommand), "-interaction=nonstopmode",
892+
cmdargs = [texcommand, "-interaction=nonstopmode",
901893
"-halt-on-error", "figure.tex"]
902894
try:
903-
check_output(cmdargs, stderr=subprocess.STDOUT, cwd=tmpdir)
895+
subprocess.check_output(
896+
cmdargs, stderr=subprocess.STDOUT, cwd=tmpdir)
904897
except subprocess.CalledProcessError as e:
905898
raise RuntimeError(
906899
"%s was not able to process your file.\n\nFull log:\n%s"
@@ -924,7 +917,7 @@ def print_pdf(self, fname_or_fh, *args, **kwargs):
924917
return
925918

926919
# figure out where the pdf is to be written to
927-
if isinstance(fname_or_fh, six.string_types):
920+
if isinstance(fname_or_fh, str):
928921
with open(fname_or_fh, "wb") as fh:
929922
self._print_pdf_to_fh(fh, *args, **kwargs)
930923
elif is_writable_file_like(fname_or_fh):
@@ -960,7 +953,7 @@ def print_png(self, fname_or_fh, *args, **kwargs):
960953
self._print_pgf_to_fh(None, *args, **kwargs)
961954
return
962955

963-
if isinstance(fname_or_fh, six.string_types):
956+
if isinstance(fname_or_fh, str):
964957
with open(fname_or_fh, "wb") as fh:
965958
self._print_png_to_fh(fh, *args, **kwargs)
966959
elif is_writable_file_like(fname_or_fh):
@@ -973,8 +966,7 @@ def get_renderer(self):
973966

974967

975968
class FigureManagerPgf(FigureManagerBase):
976-
def __init__(self, *args):
977-
FigureManagerBase.__init__(self, *args)
969+
pass
978970

979971

980972
@_Backend.export

0 commit comments

Comments
 (0)