Question re threading and serial i/o

Frank Millman frank at chagford.com
Thu Nov 6 05:51:42 EST 2003


> Frank Millman wrote:
> > 
> > def scan():
> >     p = file('/dev/ttyS0')
> >     txt = []
> >     while x:
> >         ch = p.read(1)
> 
Peter Hansen wrote:

> The last line above is the heart of the problem...
> 
> You need to use the select.select() function with a timeout, so that
> you can wake up periodically to check a flag that is set by the other
> thread, asking the i/o thread to terminate.  select() will return
> immediately if the file has data waiting to be read, so you don't
> significantly decrease the latency of the response in this way.
> 

Thanks a lot for the reply, Peter. 

I tried select(), but I cannot get it to work properly. If I show you
what I am doing, hopefully you can point out the error of my ways.

This is my Mk 2 version, that is a bit ugly, but seems to work -
    def scan():
        p = os.open('/dev/ttyS0',os.O_RDONLY|os.O_NONBLOCK)
        while x:
            try:
                print ord(os.read(p,1))
            except OSError:
                time.sleep(0.1)
        os.close(p)

This is my Mk 3 version, using select() -
    def scan():
        p = file('/dev/ttyS0')
        while x:
            ans = select.select([p],[],[],0.1)
            if ans[0]:
                print ord(p.read(1))
        p.close()

The scanner sends a string consisting of 'code' <tab> 'qty' <cr>. If I
scan a code of '1' and a quantity of '1', I would expect the program
to display 49 9 49 13. The Mk 2 version does this correctly.

The Mk 3 version behaves differently. After the first scan, it
displays 49. After each subsequent scan, it displays 9 49 13 49.

If anyone can explain what I am doing wrong, I will be most grateful.
In the meantime I am sticking with Mk 2, as it is doing the job.

Platform is Python 2.2.2 on Redhat 9.

Thanks in advance

Frank




More information about the Python-list mailing list