我有一个Python程序,它通过PySerial模块从串口读取数据.我需要记住的两个条件是:我不知道有多少数据会到达,我不知道何时需要数据.
基于此,我提出了以下代码片段:
#Code from main loop, spawning thread and waiting for data
s = serial.Serial(5, timeout=5) # Open COM5, 5 second timeout
s.baudrate = 19200
#Code from thread reading serial data
while 1:
tdata = s.read(500) # Read 500 characters or 5 seconds
if(tdata.__len__() > 0): #If we got data
if(self.flag_got_data is 0): #If it's the first data we recieved, store it
self.data = tdata
else: #if it's not the first, append the data
self.data += tdata
self.flag_got_data = 1
因此,此代码将永远循环从串行端口获取数据.我们最多可以存储500个字符的数据,然后通过设置标志来警告主循环.如果没有数据,我们就会回去睡觉并等待.
代码正常,但我不喜欢5s超时.我需要它,因为我不知道预期会有多少数据,但我不喜欢它即使没有数据也会每5秒唤醒一次.
在读取之前有没有办法检查数据何时可用?我在想Linux中的select命令.
注意:我找到了inWaiting()方