An example of python implementation controlling COM port
- 2021-07-06 11:29:48
- OfStack
Using RS232 serial port line or Class 1 interface from RS232 to USB, com port will be needed as interface for input and output modulation.
Write a script to control COM port, using Python built-in serial library
The code is as follows:
# coding=utf-8
import serial
import time
def setTout(t):
print "Old Timeout is:[%s]" % po1.getTimeout()
po1.setTimeout(t)
print "New Timeout is:[%s]" % po1.getTimeout()
def sendShell(sp,cmd):
sp.write(cmd+"\n")
print "send shell cmd:[%s]" % cmd
str = sp.readall()
return str
def shell_io(sp,cmd,sleepTime):
str = sendShell(sp,cmd)
print str
time.sleep(sleepTime)
po1 = serial.Serial('com1',115200)
timeStart = time.time()
portnow = po1.portstr
print "COM port now is:[%s]" % portnow
setTout(5)
shell_io(po1,"ls",2)
shell_io(po1,"pwd",2)
shell_io(po1,"ls -l",2)
po1.close()