[Tutor] Splitting up the input

Gonçalo Rodrigues op73418@mail.telepac.pt
Thu Jan 23 11:39:24 2003


----- Original Message -----
From: Deirdre Hackett
To: tutor@python.org
Sent: Thursday, January 23, 2003 2:22 PM
Subject: [Tutor] Splitting up the input


>I want to read in infromation from the serial port. The probem is i can
take i the whole line but only want to read it in in lumps of 9 characters.
>As in, I want to read the first 9 characters and put that into X, then read
in the next 9 characters and put that into Y...
>Any advise.
>Thanks, dee

I don't know how to get at the serial port, but supposing you can get at it
via a file object you can use the new generator facilities in Python 2.2 via
(beware: untested code)

def get(f, size):
    buffer = ''
    while True:
       #If the buffer is not enough to fulfill request get more from the
file.
        if len(buffer) < size:
            data = f.read(size)
            if not data:
                raise StopIteration
            buffer += data
        else:
            ret, buffer = buffer[:size], buffer[size:]
            yield ret

The function keeps an internal buffer,  yielding size bytes at a time. Now
you can just do

it = get(<file-object-corresponding-to-serial-port>, 9)

And use with it.next() or in a for loop.

Hope it helps,
G. Rodrigues