1. 程式人生 > >python實現控制COM口

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