Skip to content

Commit 6069ebc

Browse files
authored
pygmt.which: Refactor to get rid of temporary files (#3148)
1 parent 6193938 commit 6069ebc

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

pygmt/src/which.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,13 @@
33
"""
44

55
from pygmt.clib import Session
6-
from pygmt.helpers import (
7-
GMTTempFile,
8-
build_arg_string,
9-
fmt_docstring,
10-
kwargs_to_strings,
11-
use_alias,
12-
)
6+
from pygmt.helpers import build_arg_string, fmt_docstring, kwargs_to_strings, use_alias
137

148

159
@fmt_docstring
1610
@use_alias(G="download", V="verbose")
1711
@kwargs_to_strings(fname="sequence_space")
18-
def which(fname, **kwargs):
12+
def which(fname, **kwargs) -> str | list[str]:
1913
r"""
2014
Find the full path to specified files.
2115
@@ -56,22 +50,27 @@ def which(fname, **kwargs):
5650
5751
Returns
5852
-------
59-
path : str or list
53+
path
6054
The path(s) to the file(s), depending on the parameters used.
6155
6256
Raises
6357
------
6458
FileNotFoundError
6559
If the file is not found.
6660
"""
67-
with GMTTempFile() as tmpfile:
68-
with Session() as lib:
61+
with Session() as lib:
62+
with lib.virtualfile_out(kind="dataset") as vouttbl:
6963
lib.call_module(
7064
module="which",
71-
args=build_arg_string(kwargs, infile=fname, outfile=tmpfile.name),
65+
args=build_arg_string(kwargs, infile=fname, outfile=vouttbl),
7266
)
73-
path = tmpfile.read().strip()
74-
if not path:
75-
_fname = fname.replace(" ", "', '")
76-
raise FileNotFoundError(f"File(s) '{_fname}' not found.")
77-
return path.split("\n") if "\n" in path else path
67+
paths = lib.virtualfile_to_dataset(vfname=vouttbl, output_type="strings")
68+
69+
match paths.size:
70+
case 0:
71+
_fname = fname.replace(" ", "', '")
72+
raise FileNotFoundError(f"File(s) '{_fname}' not found.")
73+
case 1:
74+
return paths[0]
75+
case _:
76+
return paths.tolist()

0 commit comments

Comments
 (0)