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

Skip to content

Commit e43e840

Browse files
authored
Merge pull request #19115 from timhoffm/auto-backport-of-pr-19108-on-v3.3.x
Backport PR #19108 on branch v3.3.x
2 parents 8cecb03 + b3ad2b9 commit e43e840

3 files changed

Lines changed: 35 additions & 41 deletions

File tree

lib/matplotlib/animation.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,22 @@ def finish(self):
891891
interval=interval,
892892
**mode_dict))
893893

894+
# duplicate the temporary file clean up logic from
895+
# FileMovieWriter.cleanup. We can not call the inherited
896+
# versions of finished or cleanup because both assume that
897+
# there is a subprocess that we either need to call to merge
898+
# many frames together or that there is a subprocess call that
899+
# we need to clean up.
900+
if self._tmpdir:
901+
_log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
902+
self._tmpdir.cleanup()
903+
else:
904+
if self._clear_temp:
905+
_log.debug('MovieWriter: clearing temporary paths=%s',
906+
self._temp_paths)
907+
for path in self._temp_paths:
908+
path.unlink()
909+
894910

895911
class Animation:
896912
"""

lib/matplotlib/backends/backend_pgf.py

Lines changed: 17 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import subprocess
1212
import sys
1313
import tempfile
14+
from tempfile import TemporaryDirectory
1415
import weakref
1516

1617
from PIL import Image
@@ -208,7 +209,6 @@ class LatexManager:
208209
determining the metrics of text elements. The LaTeX environment can be
209210
modified by setting fonts and/or a custom preamble in `.rcParams`.
210211
"""
211-
_unclean_instances = weakref.WeakSet()
212212

213213
@staticmethod
214214
def _build_latex_header():
@@ -245,12 +245,6 @@ def _get_cached_or_new(cls):
245245
def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
246246
return cls()
247247

248-
@staticmethod
249-
def _cleanup_remaining_instances():
250-
unclean_instances = list(LatexManager._unclean_instances)
251-
for latex_manager in unclean_instances:
252-
latex_manager._cleanup()
253-
254248
def _stdin_writeln(self, s):
255249
if self.latex is None:
256250
self._setup_latex_process()
@@ -276,13 +270,10 @@ def _expect_prompt(self):
276270
return self._expect("\n*")
277271

278272
def __init__(self):
279-
# store references for __del__
280-
self._os_path = os.path
281-
self._shutil = shutil
282-
283-
# create a tmp directory for running latex, remember to cleanup
284-
self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
285-
LatexManager._unclean_instances.add(self)
273+
# create a tmp directory for running latex, register it for deletion
274+
self._tmpdir = TemporaryDirectory()
275+
self.tmpdir = self._tmpdir.name
276+
self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup)
286277

287278
# test the LaTeX setup to ensure a clean startup of the subprocess
288279
self.texcommand = mpl.rcParams["pgf.texsystem"]
@@ -311,11 +302,21 @@ def __init__(self):
311302
self.str_cache = {} # cache for strings already processed
312303

313304
def _setup_latex_process(self):
314-
# open LaTeX process for real work
305+
# Open LaTeX process for real work; register it for deletion. On
306+
# Windows, we must ensure that the subprocess has quit before being
307+
# able to delete the tmpdir in which it runs; in order to do so, we
308+
# must first `kill()` it, and then `communicate()` with it.
315309
self.latex = subprocess.Popen(
316310
[self.texcommand, "-halt-on-error"],
317311
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
318312
encoding="utf-8", cwd=self.tmpdir)
313+
314+
def finalize_latex(latex):
315+
latex.kill()
316+
latex.communicate()
317+
318+
self._finalize_latex = weakref.finalize(
319+
self, finalize_latex, self.latex)
319320
# write header with 'pgf_backend_query_start' token
320321
self._stdin_writeln(self._build_latex_header())
321322
# read all lines until our 'pgf_backend_query_start' token appears
@@ -326,23 +327,6 @@ def _setup_latex_process(self):
326327
def latex_stdin_utf8(self):
327328
return self.latex.stdin
328329

329-
def _cleanup(self):
330-
if not self._os_path.isdir(self.tmpdir):
331-
return
332-
try:
333-
self.latex.communicate()
334-
except Exception:
335-
pass
336-
try:
337-
self._shutil.rmtree(self.tmpdir)
338-
LatexManager._unclean_instances.discard(self)
339-
except Exception:
340-
sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
341-
342-
def __del__(self):
343-
_log.debug("deleting LatexManager")
344-
self._cleanup()
345-
346330
def get_width_height_descent(self, text, prop):
347331
"""
348332
Get the width, total height and descent for a text typeset by the
@@ -786,6 +770,7 @@ def add(tmpdir):
786770
TmpDirCleaner.remaining_tmpdirs.add(tmpdir)
787771

788772
@staticmethod
773+
@atexit.register
789774
def cleanup_remaining_tmpdirs():
790775
for tmpdir in TmpDirCleaner.remaining_tmpdirs:
791776
error_message = "error deleting tmp directory {}".format(tmpdir)
@@ -979,14 +964,6 @@ class _BackendPgf(_Backend):
979964
FigureCanvas = FigureCanvasPgf
980965

981966

982-
def _cleanup_all():
983-
LatexManager._cleanup_remaining_instances()
984-
TmpDirCleaner.cleanup_remaining_tmpdirs()
985-
986-
987-
atexit.register(_cleanup_all)
988-
989-
990967
class PdfPages:
991968
"""
992969
A multi-page PDF file using the pgf backend

lib/matplotlib/tests/test_image.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,8 @@ def test_load_from_url():
718718
+ ('///' if sys.platform == 'win32' else '')
719719
+ path.resolve().as_posix())
720720
plt.imread(url)
721-
plt.imread(urllib.request.urlopen(url))
721+
with urllib.request.urlopen(url) as file:
722+
plt.imread(file)
722723

723724

724725
@image_comparison(['log_scale_image'], remove_text=True)

0 commit comments

Comments
 (0)