Microsoft has provided a
COM interface to the serial port in the form of an OCX. This gives
less detailed control than the Python
package, but is adequate for the kind of examples above. It’s
distributed with Visual Basic, Visual Studio, and most Microsoft
development tools; you need one of these packages to redistribute it.
In a corporate setting this isn’t usually a problem. Unlike the
Serial package, it requires the Python COM
framework. Let’s talk to a modem with it, this time reverting
to a plain old system connected with real wires:
def MSCommDemo(): #talks to a modem on COM1 from win32com.client import Dispatch comm = Dispatch('MSCOMMLib.MSComm') comm.CommPort = 1 #COM1 comm.PortOpen = 1 try: comm.Output = "AT\015" # add a carriage return inbuf = '' now = time.time() elapsed = time.time() - now while (string.find(inbuf, 'OK') < 0) and (elapsed < 2): inbuf = inbuf + str(comm.Input) #remember the Unicode string! elapsed = time.time() - now print inbuf finally: comm.PortOpen = 0
When run, you should see your command of
echoed, followed by the response
OK. Note that you
don’t know how long it will take to respond, so you loop until
you get the desired data or until some time limit has elapsed. This
behavior was wrapped for us by Serial.py, and
you could wrap it here as well if you were going to use the
MSComm control a lot.
One truly amazing thing about the
MSComm control is the syntax. Microsoft loves properties; we saw ...