From 1453e02997f0fac068071cfcb8f53d1e0483e2aa Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Fri, 17 Feb 2023 07:01:31 +0100 Subject: [PATCH] Check file path for animation and raise if it does not exist --- lib/matplotlib/animation.py | 6 +++++- lib/matplotlib/tests/test_animation.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index 8b22fec3a3ea..3a5d0eaf6bbf 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -193,6 +193,8 @@ def setup(self, fig, outfile, dpi=None): The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file. """ + # Check that path is valid + Path(outfile).parent.resolve(strict=True) self.outfile = outfile self.fig = fig if dpi is None: @@ -405,6 +407,8 @@ def setup(self, fig, outfile, dpi=None, frame_prefix=None): deleted by `finish`; if not *None*, no temporary files are deleted. """ + # Check that path is valid + Path(outfile).parent.resolve(strict=True) self.fig = fig self.outfile = outfile if dpi is None: @@ -423,7 +427,7 @@ def setup(self, fig, outfile, dpi=None, frame_prefix=None): self.fname_format_str = '%s%%07d.%s' def __del__(self): - if self._tmpdir: + if hasattr(self, '_tmpdir') and self._tmpdir: self._tmpdir.cleanup() @property diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 2124493d3132..9f41ff5cc69c 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -506,3 +506,13 @@ def test_disable_cache_warning(anim): ) assert anim._cache_frame_data is False anim._init_draw() + + +def test_movie_writer_invalid_path(anim): + if sys.platform == "win32": + match_str = re.escape("[WinError 3] The system cannot find the path specified:") + else: + match_str = re.escape("[Errno 2] No such file or directory: '/foo") + with pytest.raises(FileNotFoundError, match=match_str): + _ = anim.save("/foo/bar/aardvark/thiscannotreallyexist.mp4", + writer=animation.FFMpegFileWriter())