Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream analog in Python

Does some analog of C# MemoryStream exist in Python (that could allow me to write binary data from some source direct into memory)? And how would I go about using it?

like image 894
illegal-immigrant Avatar asked Nov 18 '10 15:11

illegal-immigrant


2 Answers

If you are using Python >= 3.0 and tried out Adam's answer, you will notice that import StringIO or import cStringIO both give an import error. This is because StringIO is now part of the io module.

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import StringIO
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'StringIO'
>>> # Huh? Maybe this will work...
... 
>>> import cStringIO
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'cStringIO'
>>> # Whaaaa...?
... 
>>> import io
>>> io.StringIO
<class '_io.StringIO'>
>>> # Oh, good!
... 

You can use StringIO just as if it was a regular Python file: write(), close(), and all that jazz, with an additional getvalue() to retrieve the string.

like image 61
Keith Pinson Avatar answered Nov 11 '22 00:11

Keith Pinson


StringIO is one possibility: http://docs.python.org/library/stringio.html

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)...

like image 12
Adam Vandenberg Avatar answered Nov 10 '22 23:11

Adam Vandenberg