Skip to content

Commit 1134a40

Browse files
seismanweiji14
andauthored
Figure.savefig: Raise a FileNotFoundError if the parent directory doesn't exist (#2160)
Co-authored-by: Wei Ji <[email protected]>
1 parent bd05e70 commit 1134a40

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

pygmt/figure.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import base64
55
import os
66
import warnings
7+
from pathlib import Path
78
from tempfile import TemporaryDirectory
89

910
try:
@@ -251,6 +252,13 @@ def psconvert(self, icc_gray=False, **kwargs):
251252
)
252253
prefix_arg = f'-F"{prefix}"'
253254

255+
# check if the parent directory exists
256+
prefix_path = Path(prefix).parent
257+
if not prefix_path.exists():
258+
raise FileNotFoundError(
259+
f"No such directory: '{prefix_path}', please create it first."
260+
)
261+
254262
with Session() as lib:
255263
lib.call_module(
256264
module="psconvert", args=f"{prefix_arg} {build_arg_string(kwargs)}"

pygmt/tests/test_figure.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ def test_figure_savefig_exists():
8989
os.remove(fname)
9090

9191

92+
def test_figure_savefig_directory_nonexists():
93+
"""
94+
Make sure that Figure.savefig() raises a FileNotFoundError when the parent
95+
directory doesn't exist.
96+
"""
97+
fig = Figure()
98+
fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af")
99+
with pytest.raises(FileNotFoundError, match="No such directory:"):
100+
fig.savefig("a-nonexist-directory/test_figure_savefig_directory_nonexists.png")
101+
102+
92103
def test_figure_savefig_unknown_extension():
93104
"""
94105
Check that an error is raised when an unknown extension is passed.

0 commit comments

Comments
 (0)