tags:

views:

592

answers:

2

I've written a buffer class that provides a File-like interface with read, write, seek, tell, flush methods to a simple string in memory. Of course it is incomplete (e.g. I didn't write readline). It's purpose is to be filled by a background thread from some external data source, but let a user treat it like a file. I'd expect it to contain a relatively small amount of data (maybe 50K max)

Is there a better way to do this instead of writing it from scratch?

+11  A: 

You might be able to use the standard modules StringIO or cStringIO to do the same thing.

Both modules just provide a file-like in-memory object.

cStringIO is implemented in C, and will be faster, so you should use that version if you can.

Triptych
I think that's what I'm looking for. But are these classes thread-safe? I will have separate reader and writer threads.
djs
Pythons GIL means that thread safety is highly unlikely to be a problem, as two threads don't execute at the same time.
Lennart Regebro
That doesn't make it thread-safe. If it did, then we wouldn't need thread safety on single-core processors.
Kylotan
+4  A: 

I think you might be looking for StringIO.

Randy Morris