Question regarding serial port communication with python.

jackxh at jackxh at
Thu Nov 2 19:02:24 CET 2000

Hi everyone:
I got following piece code from newsgroup and made some small
modification. It runs, but in order to determine how many bye to read,
the script has to search for '\n'. I don't like this because a lot of
times the serial port give you back a lot of "\n" in the data. I was
wondering if there is an function that is simular to but
doesn't require you to input a number for the byte to read.  In stead,
it will through back the data or message back like a telnet session.

Thanks a lot.

Jack Xie

#	Actual Code --------------------------
import os, termios

class SerialPort:
    """Basic serial port class.

    This simply encapsulates a file descriptor for the desired serial

    def __init__(self, dev):
        print dev
        fd = self.fd =, FCNTL.O_RDWR)

        self.original_state = termios.tcgetattr(fd)

        L = termios.tcgetattr(fd)
        iflag, oflag, cflag, lflag, ispeed, ospeed, chars = L
        ispeed = ospeed = TERMIOS.B9600
        cflag = (cflag & ~TERMIOS.CSIZE) | TERMIOS.CS8 | TERMIOS.CSTOP
        cflag = (cflag | TERMIOS.CLOCAL | TERMIOS.CREAD) &
        iflag = TERMIOS.IGNBRK
        lflag = 0
        oflag = 0
        chars[ TERMIOS.VMIN ] = 1
        chars[ TERMIOS.VTIME ] = 5
        iflag = iflag & ~(TERMIOS.IXON | TERMIOS.IXOFF | TERMIOS.IXANY)
        cflag = cflag & ~(TERMIOS.PARENB | TERMIOS.PARODD)
        L = [iflag, oflag, cflag, lflag, ispeed, ospeed, chars]
        termios.tcsetattr(fd, TERMIOS.TCSANOW, L)
        L = termios.tcgetattr(fd)

    def write(self, string):
        "Write a string to the port"
        os.write(self.fd, string)
#        termios.tcdrain(self.fd)
#        termios.tcflush(self.fd, TERMIOS.TCOFLUSH)

    def read(self, N=1):
        "Read a string from the port"
        return, N)

    def close(self):
        termios.tcsetattr(self.fd, TERMIOS.TCSANOW, self.original_state)
        if self.fd is None: return
        os.close( self.fd )
        self.fd = None

def test(args = None):
    while 1:
        c =
        print c
        if c == '\n': break


if __name__ == '__main__':

Sent via
Before you buy.

More information about the Python-list mailing list