mirror of
https://github.com/wassname/scikit-image.git
synced 2026-06-27 21:08:24 +08:00
af1f567108
This provides writeable filenames that are cleaned up when the context is exited.
28 lines
759 B
Python
28 lines
759 B
Python
from tempfile import NamedTemporaryFile
|
|
from contextlib import contextmanager
|
|
import os
|
|
|
|
@contextmanager
|
|
def temporary_file(suffix=''):
|
|
"""Yield a writeable temporary filename that is deleted on context exit.
|
|
|
|
Parameters
|
|
----------
|
|
suffix : string, optional
|
|
The suffix for the file.
|
|
|
|
Examples
|
|
--------
|
|
>>> import numpy as np
|
|
>>> from skimage import io
|
|
>>> with temporary_file('.tif') as tempfile:
|
|
... im = np.zeros((5, 5), np.uint8)
|
|
... io.imsave(tempfile, im)
|
|
... assert np.all(io.imread(tempfile) == im)
|
|
"""
|
|
tempfile_stream = NamedTemporaryFile(suffix=suffix, delete=False)
|
|
tempfile = tempfile_stream.name
|
|
tempfile_stream.close()
|
|
yield tempfile
|
|
os.remove(tempfile)
|