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

Skip to content

Cairo backend reports file closed on writing to SVGZ file format. #1883

@arkottke

Description

@arkottke

With this simple test case:

import matplotlib
matplotlib.use('Cairo')
import matplotlib.pyplot as plt

import numpy as np

x = np.arange(-10, 10)
y = x ** 2

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x, y, 'b-')

ax.grid()

fig.savefig('test.svgz')

The following error is reported on Windows 7 with Python 3.3.

$ python test.py
Traceback (most recent call last):
  File "test.py", line 21, in <module>
    fig.savefig('test.svgz')
  File "C:\Python33\lib\site-packages\matplotlib\figure.py", line 1364, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "C:\Python33\lib\site-packages\matplotlib\backend_bases.py", line 2093, in print_figure
    **kwargs)
  File "C:\Python33\lib\site-packages\matplotlib\backends\backend_cairo.py", line 437, in print_svgz
    return self._save(fobj, 'svgz', *args, **kwargs)
  File "C:\Python33\lib\site-packages\matplotlib\backends\backend_cairo.py", line 514, in _save
    surface.finish()
  File "C:\Python33\lib\gzip.py", line 325, in write
    self._check_closed()
  File "C:\Python33\lib\gzip.py", line 244, in _check_closed
    raise ValueError('I/O operation on closed file.')
ValueError: I/O operation on closed file.

The error has to do with the create of the file object on line 466 of backend_cairo.py.

            if format == 'svgz':
                filename = fo
                if is_string_like(fo):
                    fo = open(fo, 'wb')
                    close = True
                else:
                    close = False
                try:
                    fo = gzip.GzipFile(None, 'wb', fileobj=fo)
                finally:
                    if close:
                        fo.close()

If I am reading the logic right, the file object is closed if a filename is provided. I would propose the following change:

            if format == 'svgz':
                filename = fo
                if is_string_like(fo):
                    fo = open(fo, 'wb')

                fo = gzip.GzipFile(None, 'wb', fileobj=fo)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions