Reading HTTP response from UART I'm using a Telit GE864-GPS modem, which runs a dialect of Python 1.5.2. The Python module has access to the modem using a buffered UART, which may still be receiving when reading starts. The following code makes sure the entire response is read, and return either the response body or '0' on timeout.

def receiveReponse ( ):

    # MOD.secCounter() provides the current time in seconds
    timeout = MOD.secCounter() + 10

    str = ""
    length = ""
    newlinepos = 0

    while ( MOD.secCounter() &lt; timeout ):

        newlinepos = str.find("\n\r")

        if ( (newlinepos != -1) and not length ):

            newlinepos = newlinepos + 2
            pos = str.find("Content-Length:") + 15

            while ( str[pos] != '\n' ):
                length = "%s%s" % (length, str[pos])
                pos = pos + 1

            length = int(length) + newlinepos

        else:
            MOD.sleep(5)

            # MDM receive reads the current UART buffer
            str = str + MDM.receive(1)

        if ( length and len(str) &gt;= length ):
            return str[newlinepos:(newlinepos+length)]

    return 0


The entire procedure seems rather overcomplicated. Am I missing some obvious simplifications?
This

        while ( str[pos] != '\n' ):
            length = "%s%s" % (length, str[pos])
            pos = pos + 1


could be just

        length = string.split(str[pos:], '\n')[0]