enhancedserial.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 """Enhanced Serial Port class
00003 part of pyserial (http://pyserial.sf.net)  (C)2002 cliechti@gmx.net
00004 
00005 another implementation of the readline and readlines method.
00006 this one should be more efficient because a bunch of characters are read
00007 on each access, but the drawback is that a timeout must be specified to
00008 make it work (enforced by the class __init__).
00009 
00010 this class could be enhanced with a read_until() method and more
00011 like found in the telnetlib.
00012 """
00013 
00014 from serial import Serial
00015 
00016 class EnhancedSerial(Serial):
00017     def __init__(self, *args, **kwargs):
00018         #ensure that a reasonable timeout is set
00019         timeout = kwargs.get('timeout',0.1)
00020         #if timeout < 0.01: timeout = 0.1
00021         kwargs['timeout'] = timeout
00022         Serial.__init__(self, *args, **kwargs)
00023         self.buf = ''
00024         
00025     def readline(self, maxsize=None, timeout=1, eol='\n'):
00026         """maxsize is ignored, timeout in seconds is the max time that is way for a complete line"""
00027         tries = 0
00028         while 1:
00029             self.buf += self.read(512)
00030             pos = self.buf.find(eol)
00031             if pos >= 0:
00032                 line, self.buf = self.buf[:pos+1], self.buf[pos+1:]
00033                 return line
00034             tries += 1
00035             if tries * self.timeout > timeout:
00036                 break
00037         line, self.buf = self.buf, ''
00038         return line
00039 
00040     def readlines(self, sizehint=None, timeout=1, eol='\n'):
00041         """read all lines that are available. abort after timout
00042         when no more data arrives."""
00043         lines = []
00044         while 1:
00045             line = self.readline(timeout=timeout, eol=eol)
00046             if line:
00047                 lines.append(line)
00048             if not line or line[-1:] != eol:
00049                 break
00050         return lines
00051 
00052 if __name__=='__main__':
00053     #do some simple tests with a Loopback HW (see test.py for details)
00054     PORT = 0
00055     #test, only with Loopback HW (shortcut RX/TX pins (3+4 on DSUB 9 and 25) )
00056     s = EnhancedSerial(PORT)
00057     #write out some test data lines
00058     s.write('\n'.join("hello how are you".split()))
00059     #and read them back
00060     print s.readlines()
00061     #this one should print an empty list
00062     print s.readlines(timeout=0.4)


serializer
Author(s): Patrick Goebel
autogenerated on Sun Jan 5 2014 11:31:58