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

Skip to content

Commit 184a408

Browse files
authored
Merge pull request #10474 from anntzer/tempdir
MNT: Use TemporaryDirectory instead of mkdtemp in a few places.
2 parents aae55fc + 33a2624 commit 184a408

File tree

5 files changed

+28
-48
lines changed

5 files changed

+28
-48
lines changed

lib/matplotlib/backends/backend_pgf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -311,12 +311,12 @@ def _cleanup(self):
311311
self.latex.communicate()
312312
self.latex_stdin_utf8.close()
313313
self.latex.stdout.close()
314-
except:
314+
except Exception:
315315
pass
316316
try:
317317
self._shutil.rmtree(self.tmpdir)
318318
LatexManager._unclean_instances.discard(self)
319-
except:
319+
except Exception:
320320
sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
321321

322322
def __del__(self):

lib/matplotlib/backends/backend_ps.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import shutil
1414
import subprocess
1515
import sys
16-
from tempfile import mkstemp
16+
from tempfile import TemporaryDirectory
1717
import time
1818

1919
import numpy as np
@@ -1150,19 +1150,15 @@ def print_figure_impl(fh):
11501150
if rcParams['ps.usedistiller']:
11511151
# We are going to use an external program to process the output.
11521152
# Write to a temporary file.
1153-
fd, tmpfile = mkstemp()
1154-
try:
1155-
with open(fd, 'w', encoding='latin-1') as fh:
1153+
with TemporaryDirectory() as tmpdir:
1154+
tmpfile = os.path.join(tmpdir, "tmp.ps")
1155+
with open(tmpfile, 'w', encoding='latin-1') as fh:
11561156
print_figure_impl(fh)
11571157
if rcParams['ps.usedistiller'] == 'ghostscript':
11581158
gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)
11591159
elif rcParams['ps.usedistiller'] == 'xpdf':
11601160
xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)
1161-
11621161
_move_path_to_path_or_stream(tmpfile, outfile)
1163-
finally:
1164-
if os.path.isfile(tmpfile):
1165-
os.unlink(tmpfile)
11661162

11671163
else:
11681164
# Write directly to outfile.
@@ -1255,9 +1251,9 @@ def write(self, *kl, **kwargs):
12551251

12561252
# write to a temp file, we'll move it to outfile when done
12571253

1258-
fd, tmpfile = mkstemp()
1259-
try:
1260-
with open(fd, 'w', encoding='latin-1') as fh:
1254+
with TemporaryDirectory() as tmpdir:
1255+
tmpfile = os.path.join(tmpdir, "tmp.ps")
1256+
with open(tmpfile, 'w', encoding='latin-1') as fh:
12611257
# write the Encapsulated PostScript headers
12621258
print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
12631259
if title:
@@ -1344,9 +1340,6 @@ def write(self, *kl, **kwargs):
13441340
rotated=psfrag_rotated)
13451341

13461342
_move_path_to_path_or_stream(tmpfile, outfile)
1347-
finally:
1348-
if os.path.isfile(tmpfile):
1349-
os.unlink(tmpfile)
13501343

13511344

13521345
def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,

lib/matplotlib/tests/test_animation.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
from pathlib import Path
33
import sys
4-
import tempfile
54

65
import numpy as np
76
import pytest

lib/matplotlib/tests/test_backend_bases.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
1-
from matplotlib.backend_bases import FigureCanvasBase
2-
from matplotlib.backend_bases import RendererBase
3-
from matplotlib.backend_bases import LocationEvent
4-
1+
from matplotlib.backend_bases import (
2+
FigureCanvasBase, LocationEvent, RendererBase)
53
import matplotlib.pyplot as plt
64
import matplotlib.transforms as transforms
75
import matplotlib.path as path
86

97
import numpy as np
10-
import os
11-
import shutil
12-
import tempfile
138
import pytest
149

1510

@@ -52,16 +47,12 @@ def check(master_transform, paths, all_transforms,
5247
check(id, paths, tforms, offsets, facecolors[0:1], edgecolors)
5348

5449

55-
def test_get_default_filename():
56-
try:
57-
test_dir = tempfile.mkdtemp()
58-
plt.rcParams['savefig.directory'] = test_dir
59-
fig = plt.figure()
60-
canvas = FigureCanvasBase(fig)
61-
filename = canvas.get_default_filename()
62-
assert filename == 'image.png'
63-
finally:
64-
shutil.rmtree(test_dir)
50+
def test_get_default_filename(tmpdir):
51+
plt.rcParams['savefig.directory'] = str(tmpdir)
52+
fig = plt.figure()
53+
canvas = FigureCanvasBase(fig)
54+
filename = canvas.get_default_filename()
55+
assert filename == 'image.png'
6556

6657

6758
@pytest.mark.backend('pdf')

lib/matplotlib/tests/test_style.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
from contextlib import contextmanager
33
import gc
44
import os
5+
from pathlib import Path
56
import shutil
6-
import tempfile
7+
from tempfile import TemporaryDirectory
78
import warnings
89

910
import pytest
@@ -12,6 +13,7 @@
1213
from matplotlib import pyplot as plt, style
1314
from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
1415

16+
1517
PARAM = 'image.cmap'
1618
VALUE = 'pink'
1719
DUMMY_SETTINGS = {PARAM: VALUE}
@@ -23,21 +25,16 @@ def temp_style(style_name, settings=None):
2325
if not settings:
2426
settings = DUMMY_SETTINGS
2527
temp_file = '%s.%s' % (style_name, STYLE_EXTENSION)
26-
27-
# Write style settings to file in the temp directory.
28-
tempdir = tempfile.mkdtemp()
29-
with open(os.path.join(tempdir, temp_file), 'w') as f:
30-
for k, v in settings.items():
31-
f.write('%s: %s' % (k, v))
32-
33-
# Add temp directory to style path and reload so we can access this style.
34-
USER_LIBRARY_PATHS.append(tempdir)
35-
style.reload_library()
36-
3728
try:
38-
yield
29+
with TemporaryDirectory() as tmpdir:
30+
# Write style settings to file in the tmpdir.
31+
Path(tmpdir, temp_file).write_text(
32+
"\n".join("{}: {}".format(k, v) for k, v in settings.items()))
33+
# Add tmpdir to style path and reload so we can access this style.
34+
USER_LIBRARY_PATHS.append(tmpdir)
35+
style.reload_library()
36+
yield
3937
finally:
40-
shutil.rmtree(tempdir)
4138
style.reload_library()
4239

4340

0 commit comments

Comments
 (0)