串口超级命令行

import serial
from serial.tools import list_ports
timex = 0.5
ls = [115200,19200,9600]
while 1:
try:
port_list = list(list_ports.comports())
if len(port_list) == 0:
input("无可用串口,按回车键刷新串口列表...")
continue
else:
while 1:
lis = []
num1 = []
print("按数字键回车来选择对应的串口:")
for i in range(0, len(port_list)):
print("->".rjust(6),i,str(port_list[i]).split()[0])
lis.append(str(port_list[i]).split()[0])
num1.append(i)
try:
num = int(input())
if num in num1:
portx = lis[num]
break
else:
print("\u001b[31m输入不存在,请重新输入\u001b[0m")
continue
except Exception as e:
print("\u001b[31m你输入不合法,请重新输入\u001b[0m")
continue
while 1:
num2 = []
print("选择波特率:")
for i in range(0,len(ls)):
print("->".rjust(6),i,ls[i])
num2.append(i)
try:
s1 = int(input(""))
if s1 in num2:
bps = int(ls[s1])
break
else:
print("\u001b[31m输入不存在,请重新输入\u001b[0m")
continue
except Exception as e:
print("\u001b[31m输入不合法,请重新输入\u001b[0m")
continue

s2 = input("已进入终端模式,按回车进入,或输入q退出:")
while 1:
ser = serial.Serial(portx, bps, timeout=timex)
if s2 == "q":
ser.close()
break
else:
result = ser.write(b'\r\n')
if str(ser.read(result)) == "b''":
print("\u001b[31m串口与设备不匹配,请重新连接\u001b[0m")
ser.close()
break
else:
print(ser.read(200).decode("GBK"), end="")
while 1:
st = input("")
if st == "":
s = st + "\r\n"
re = ser.write(s.encode("GBk"))
if str(ser.read(re)) == "b''":
ser.close()
break
else:
print(ser.read(200).decode("GBK"),end="")
else:
s = st + "\r\n"
re = ser.write(s.encode("GBk"))
if str(ser.read(re)) == "b''":
ser.close()
break
print(ser.read(200).decode("GBK"),end="")
except Exception as e:
print("\u001b[31m" + portx, "串口被占用,关闭后重试\u001b[0m")
continue

  上一篇:文件的上传校验 下一篇:github超时解决  

湘ICP备19016894号 © 2019 小钱