Serial programming

Michael P. Reilly arcege at
Fri Jun 11 11:39:58 EDT 1999

DORAEMON.HK <abc at def.ghi.jkl> wrote:
: I am looking for some example in python about send and receive data from
: serial port.  Like send "ATZ" and receive "OK".  Any help?? Thanks a lot!!

You can open the device file directly and handle the information
yourself.  UNIX devices are handle just like files.  You can change
device attributes (speed, parity, etc.) with the termios module or
fcntl.ioctl function.

  modem = open('/dev/cua0', 'r+')
  f =
  if f[:2] != 'OK':
    raise ValueError, "modem not okay"

There are some Expect modules/extensions around that could help you as
well;  my ExpectPy extention is at  You can find others
through the Python website.

  import ExpectPy
  modem = ExpectPy.spawnfile(open('/dev/cua0', 'r+'))
    f = modem.expect(
      (ExpectPy.EXACT, "OK\r\n", "OK"),
      (ExpectPy.GLOB, "*\r\n", "Not OK")
    if f == "Not OK":
      raise ValueError, "modem not okay"
  except (ValueError, ExpectPy.TimeoutError), value:
    raise ValueError, value

I hope this helps.


More information about the Python-list mailing list