Skip to content

Commit b084960

Browse files
committed
Implement tempfile_from_buffer for io.StringIO inputs
1 parent fc246e7 commit b084960

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

pygmt/helpers/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Functions, classes, decorators, and context managers to help wrap GMT modules.
33
"""
44
from .decorators import fmt_docstring, use_alias, kwargs_to_strings
5-
from .tempfile import GMTTempFile, unique_name
5+
from .tempfile import GMTTempFile, tempfile_from_buffer, unique_name
66
from .utils import (
77
data_kind,
88
dummy_context,

pygmt/helpers/tempfile.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
Utilities for dealing with temporary file management.
33
"""
44
import os
5+
import shutil
56
import uuid
7+
from contextlib import contextmanager
68
from tempfile import NamedTemporaryFile
79

810
import numpy as np
@@ -105,3 +107,49 @@ def loadtxt(self, **kwargs):
105107
106108
"""
107109
return np.loadtxt(self.name, **kwargs)
110+
111+
112+
@contextmanager
113+
def tempfile_from_buffer(buf):
114+
"""
115+
Store an io.StringIO buffer stream inside a temporary text file.
116+
117+
Use the temporary file name to pass in data in your string buffer to a GMT
118+
module.
119+
120+
Context manager (use in a ``with`` block). Yields the temporary file name
121+
that you can pass as an argument to a GMT module call. Closes the
122+
temporary file upon exit of the ``with`` block.
123+
124+
Parameters
125+
----------
126+
buf : io.StringIO
127+
The in-memory text stream buffer that will be included in the temporary
128+
file.
129+
130+
Yields
131+
------
132+
fname : str
133+
The name of temporary file. Pass this as a file name argument to a GMT
134+
module.
135+
136+
Examples
137+
--------
138+
139+
>>> import io
140+
>>> from pygmt.helpers import tempfile_from_buffer
141+
>>> from pygmt import info
142+
>>> data = np.arange(0, 6, 0.5).reshape((4, 3))
143+
>>> buf = io.StringIO()
144+
>>> np.savetxt(fname=buf, X=data, fmt="%.1f")
145+
>>> with tempfile_from_buffer(buf=buf) as fname:
146+
... result = info(fname, per_column=True)
147+
... print(result.strip())
148+
0 4.5 0.5 5 1 5.5
149+
"""
150+
with GMTTempFile() as tmpfile:
151+
buf.seek(0) # Change stream position back to start
152+
with open(file=tmpfile.name, mode="w") as fdst:
153+
shutil.copyfileobj(fsrc=buf, fdst=fdst)
154+
155+
yield tmpfile.name

0 commit comments

Comments
 (0)