Skip to content

Commit 820a326

Browse files
committed
Fixes #1862: The PS backend would inadvertently close file handles passed to it on Python 3. The TextIOWrapper that handles the encoding from unicode to ascii needs to be detached before its destructor is called, otherwise it will call close on the underlying file object. Also cleans up how with statements are handled to avoid the sometimes problematic null contextmanager.
1 parent baaf1f4 commit 820a326

File tree

1 file changed

+19
-21
lines changed

1 file changed

+19
-21
lines changed

lib/matplotlib/backends/backend_ps.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
# PY3KTODO: Get rid of "print >>fh" syntax
66

77
from __future__ import division, print_function
8-
import contextlib
98
import glob, math, os, shutil, sys, time
109
def _fn_name(): return sys._getframe(1).f_code.co_name
1110
import io
@@ -974,11 +973,6 @@ def print_ps(self, outfile, *args, **kwargs):
974973
def print_eps(self, outfile, *args, **kwargs):
975974
return self._print_ps(outfile, 'eps', *args, **kwargs)
976975

977-
978-
979-
980-
981-
982976
def _print_ps(self, outfile, format, *args, **kwargs):
983977
papertype = kwargs.pop("papertype", rcParams['ps.papersize'])
984978
papertype = papertype.lower()
@@ -1106,21 +1100,7 @@ def write(self, *kl, **kwargs):
11061100
self.figure.set_facecolor(origfacecolor)
11071101
self.figure.set_edgecolor(origedgecolor)
11081102

1109-
if rcParams['ps.usedistiller']:
1110-
# We are going to use an external program to process the output.
1111-
# Write to a temporary file.
1112-
fd, tmpfile = mkstemp()
1113-
context_manager = io.open(fd, 'wb')
1114-
else:
1115-
# Write directly to outfile.
1116-
if passed_in_file_object:
1117-
@contextlib.contextmanager
1118-
def null_context(value):
1119-
yield value
1120-
context_manager = null_context(outfile)
1121-
else:
1122-
context_manager = open(outfile, 'wb')
1123-
with context_manager as raw_fh:
1103+
def print_figure_impl():
11241104
if sys.version_info[0] >= 3:
11251105
fh = io.TextIOWrapper(raw_fh, encoding="ascii")
11261106
else:
@@ -1195,6 +1175,24 @@ def null_context(value):
11951175
if not isEPSF: print("%%EOF", file=fh)
11961176
fh.flush()
11971177

1178+
if sys.version_info[0] >= 3:
1179+
fh.detach()
1180+
1181+
if rcParams['ps.usedistiller']:
1182+
# We are going to use an external program to process the output.
1183+
# Write to a temporary file.
1184+
fd, tmpfile = mkstemp()
1185+
with io.open(fd, 'wb') as raw_fh:
1186+
print_figure_impl()
1187+
else:
1188+
# Write directly to outfile.
1189+
if passed_in_file_object:
1190+
raw_fh = outfile
1191+
print_figure_impl()
1192+
else:
1193+
with open(outfile, 'wb') as raw_fh:
1194+
print_figure_impl()
1195+
11981196
if rcParams['ps.usedistiller']:
11991197
if rcParams['ps.usedistiller'] == 'ghostscript':
12001198
gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)

0 commit comments

Comments
 (0)