#! python3
import serial #導入模塊
import time
import sys
# 傳入參數,當傳入的參數只有命令時,默認測試超時爲2秒
argvs = sys.argv[1:]
command = sys.argv[1] + "\r\n"
timeOut = 2
if len(argvs)>1:
timeOut = int(sys.argv[2])
try:
#端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
portx="/dev/cu.usbserial-Fixture"
#波特率,標準值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200,230400
bps=115200
#超時設置,None:永遠等待操作,0爲立即返回請求結果,其他值爲等待超時時間(單位爲秒)
timex=5
# 打開串口,並得到串口對象
ser=serial.Serial(portx,bps,timeout=timex)
print("串口名稱:",ser.port)#獲取到當前打開的串口名
print("串口波特率:",ser.baudrate)#獲取波特率
result=ser.write(command.encode("gbk"))#寫數據
#print(ser.read())#讀一個字節
# print(ser.read(10).decode("gbk"))#讀十個字節
#print(ser.readline().decode("gbk"))#讀一行
#print(ser.readlines())#讀取多行,返回列表,必須匹配超時(timeout)使用
#print(ser.in_waiting)#獲取輸入緩衝區的剩餘字節數
#print(ser.out_waiting)#獲取輸出緩衝區的字節數
result = ""
startTime = time.time()
while True:
endTime = time.time()
if endTime - startTime > timeOut: #超時時,測試結束
break
if ser.in_waiting:
str=ser.read(ser.in_waiting).decode("gbk")
if str.find(">>")>-1: #檢測到“>>”時,測試結束
result = result + str
break
else:
result=result+str
print("讀取串口數據:",result)
print("讀取時間:",startTime-endTime)
print("------ end --------")
ser.close() #關閉串口
except Exception as e:
print("---異常---:",e)
終端中運行:1. cd到文件所在目錄
2.python3 serialport.py 參數1 參數2