python实现控制COM口

使用RS232串口线或者是RS232转USB的这一类的接口,会需要com口作为接口来进行输入输出调式,


写了个脚本来控制COM口,用到了Python内建的serial库

代码如下:

# 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()




你可能感兴趣的:(工具)