writing serial port data to the gzip file

Leo Kislov Leo.Kislov at gmail.com
Sun Dec 17 21:05:50 EST 2006


Petr Jakes wrote:
> I am trying to save data it is comming from the serial port continually
> for some period.
> (expect reading from serial port is 100% not a problem)
> Following is an example of the code I am trying to write. It works, but
> it produce an empty gz file (0kB size) even I am sure I am getting data
> from the serial port. It looks like g.close() does not close the gz
> file.
> I was reading in the doc:
>
> Calling a GzipFile object's close() method does not close fileobj,
> since you might wish to append more material after the compressed
> data...
>
> so I am completely lost now...
>
> thanks for your comments.
> Petr Jakes
> ==== snippet of the code  ====
> def dataOnSerialPort():
>     data=s.readLine()
>     if data:
>         return data
>     else:
>         return 0
>
> while 1:
>     g=gzip.GzipFile("/root/foofile.gz","w")
>     while dataOnSerialPort():
>         g.write(data)
>     else: g.close()

Your while loop is discarding result of dataOnSerialPort, so you're
probably writing empty string to the file many times. Typically this
kind of loop are implemented using iterators. Check if your s object
(is it from external library?) already implements iterator. If it does
then

for data in s:
    g.write(data)

is all you need. If it doesn't, you can use iter to create iterator for
you:

for data in iter(s.readLine, ''):
    g.write(data)

  -- Leo




More information about the Python-list mailing list