struct.unpack() on a stream

U

Ulrich Eckhardt

Hi!

I have a socket from which I would like to parse some data, how would I do
that? Of course, I can manually read data from the socket until unpack()
stops complaining about a lack of data, but that sounds rather inelegant.

Any better suggestions?

Uli
 
G

Gabriel Genellina

En Fri, 27 Feb 2009 09:29:16 -0200, Ulrich Eckhardt
I have a socket from which I would like to parse some data, how would I
do
that? Of course, I can manually read data from the socket until unpack()
stops complaining about a lack of data, but that sounds rather inelegant.

Any better suggestions?

Read until you get the required bytes; use the size attribute.
 
M

MRAB

Gabriel said:
En Fri, 27 Feb 2009 09:29:16 -0200, Ulrich Eckhardt


Read until you get the required bytes; use the size attribute.
The struct module has a function called "calcsize", eg:
2

That will tell you how many bytes to read.
 
G

Gabriel Genellina

The struct module has a function called "calcsize", eg:

2

That will tell you how many bytes to read.

The struct module defines also a Struct class; instead of using the module
functions, it's more efficient to create a Struct instance and call its
methods when one is going to use the same format more than once:

py> s = struct.Struct("<H")
py> s.size
2
py> s.unpack("\x40\x00")
(64,)

That's the size attribute I was talking about - too tersely perhaps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,529
Members
48,240
Latest member
เพิ่มไลค์|LikePro

Latest Threads

Top