Bullet proof passing numeric values from NMEA data stream.

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Mar 20 09:45:38 EDT 2007


On Wed, 21 Mar 2007 00:29:00 +1100, Steven D'Aprano wrote:

> All your examples include spurious whitespace. If that is the only
> problem, here's a simple fix:
> 
> def despace(s):
>     """Remove whitespace from string s."""
>     return 

Gah! Ignore that stub. I forgot to delete it :(


While I'm at it, here's another solution: simply skip invalid values,
using a pair of iterators, one to collect raw values from the device and
one to strip out the invalid results.

def raw_data():
    """Generator to collect raw data and pass it on."""
    while 1:
        # grab a single value
        value = grab_data_value_from_somewhere()
        if value is "": # Some special "END TRANSMISSION" value.
            return
        yield value

def converter(stream):
    """Generator to strip out values that can't be converted to float."""
    for value in stream:
        try:
            yield float(value)
        except ValueError:
            pass

values_safe_to_use = converter(raw_data())

for value in values_safe_to_use:
    print value


Naturally you can extend the converter to try harder to convert the string
to a float before giving up.


-- 
Steven.




More information about the Python-list mailing list