[Tutor] COM Ports
Michael P. Reilly
arcege@speakeasy.net
Fri, 20 Apr 2001 17:35:13 -0400 (EDT)
kromag@nsacom.net wrote
> I am using (at this moment) linux for this particular job, but would have no
> problem switching to Free/NetBSD (I don't think PostGreSQL will run on
> OpenBSD yet...). As I understand it, one has to create a C module to read
> from the serial port in python under unix. I have read the Linux-Serial-
> Programming-HOWTO and the C Extentions Overview in Programming Python and am
> beginning to get some idea of how creating such a mawnstah might work, but
> would really like to see some example code that is a little less generic.
You don't need to create a new C module just to access the serial lines,
open the device file for the serial line (eg. /dev/ttyS0), configure the
line as needed with the termios/TERMIOS modules and read and write the
data as needed. The select module can help you for when data is ready.
>>> import termios, TERMIOS
>>> f= open('/dev/ttyS2', 'r+')
>>> settings = termios.tcgetattr(f.fileno())
>>> settings[3] = settings[3] & ~TERMIOS.ICANON
>>> settings[4] = settings[5] = TERMIOS.B9600
>>> termios.tcsetattr(f.fileno(), settings, TERMIOS.TCSAFLUSH)
>>> f.write('AT\r') # Hayes modem protocol
>>> f.read(10)
'AT\n' # this is contrived, it might return 'AT\r\n'
>>>
There are other packages out there that will do this for you as well.
[Shameless self-promotion] Such as ExpectPy, which is a C module interface
to the Expect library (usually associated with Tcl); it doesn't sound
like you need ExpectPy though. Definately look into termios.
Myself, as a developer of FreeBSD products, I'd stay with Linux.
There are a lot of problems that FreeBSD creates (and if you were to
use FreeBSD, do NOT use the canned Python 1.5.2 in the distributions,
build it yourself).
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |