|
2 | 2 | Utilities for dealing with temporary file management.
|
3 | 3 | """
|
4 | 4 | import os
|
| 5 | +import shutil |
5 | 6 | import uuid
|
| 7 | +from contextlib import contextmanager |
6 | 8 | from tempfile import NamedTemporaryFile
|
7 | 9 |
|
8 | 10 | import numpy as np
|
@@ -105,3 +107,49 @@ def loadtxt(self, **kwargs):
|
105 | 107 |
|
106 | 108 | """
|
107 | 109 | 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