我是python和串行端口的新手。我想连续监视串口。如果未打开端口或拒绝访问,则需要不停运行python脚本。我做了些什么,但是当PORT未打开或访问被拒绝时,该脚本已停止。请帮助某人解决此问题。
import serial
z1baudrate = 9600
z1port = 'COM4'
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
try:
if z1serial.is_open:
while True:
size = z1serial.inWaiting()
if size:
data = z1serial.read(size)
res= data.decode("utf-8")
print(res)
else:
print("Data not reading")
time.sleep(1)
else:
z1serial.close()
print('z1serial not open or Already in use')
except serial.SerialException as e:
z1serial.close()
print('COM4 not open')
您需要在z1serial
块中包含try
分配为
import serial
import time
z1baudrate = 9600
z1port = 'COM4'
while True:
try:
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
if z1serial.is_open:
while True:
size = z1serial.inWaiting()
if size:
data = z1serial.read(size)
res= data.decode("utf-8")
print(res)
else:
print("Data not reading")
time.sleep(1)
else:
z1serial.close()
print('z1serial not open or Already in use')
except serial.SerialException:
print('COM4 not open')
time.sleep(1)
这对我有用,在Python 3.7上运行