tags:

views:

388

answers:

2

These functions (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?

Also, their write*datatype*() counterparts too.

+4  A: 

I think struct.unpack_from is what you're looking for.

Swaroop C H
indeed sir, thank you.
ryeguy
A: 

Note that Python doesn't have readByte, readInt and readString because it doesn't work directly with all those fancy data types. Files provides strings which you can convert.

Python <= 2.6 has String and that's what you get from your input streams -- strings. The simple socket.read() provides this input. You can use struct to convert the stream into a sequence of integers. What's important is that the pack and unpack conversions may be by byte, word, long, or whatever, but the Python result is integers.

So your input may be bytes, but Python represents this as a string, much of which is unprintable. Your desire may be an array of individual values, each between 0 and 255, that are the numeric versions of those bytes. Python represents these as integers.

Python >= 3.0 has bytearrays that can be used to process bytes directly. You'll can convert them to strings, or integers (which include bytes and longs) or whatever.

S.Lott