I'm unit testing code in Python2.7 that writes numpy array via ndarray.tofile(fileHandle,..). Since doing file IO in unit tests is bad for a number of reasons, how do I substitute a byte memorystream in place of the file handle? (io.BytesIO failed to work because ndarray.toFile() asks it for a file name.)
2 Answers 2
Shouldn't tobytes [1] and frombuffer [2] do what you need for testing purposes?
m = np.random.rand(5,3)
b = m.tobytes()
mb = np.frombuffer(b).reshape(m.shape)
1 Comment
Would a tempfile.TemporaryFile suit your purposes?
It exposes the same interface as a normal file object, so you can pass it directly to np.ndarray.tofile(), and it will be deleted immediately when it is either explicitly closed or garbage collected:
import numpy as np
from tempfile import TemporaryFile
x = np.random.randn(1000)
with TemporaryFile() as t:
x.tofile(t)
# do your testing...
# t is closed and deleted
It will, however, reside temporarily on disk (usually in /tmp/ on a Linux machine), but I don't see an easy way to avoid I/O altogether, since .tofile() will ultimately need a valid OS-level file descriptor.
6 Comments
tofile?npy_PyFile_Dup2 (note the use of os.dup to duplicate a file descriptor). This is all going on at C level, so I don't see an easy way to fake an open file via a Python object.Explore related questions
See similar questions with these tags.