import serial
ser = serial.Serial('COM5', baudrate=9600, parity=serial.PARITY_NONE, timeout=1)
print "connected to: " + ser.portstr
while ser.isOpen():
line = ser.readline().strip()
if len(line)==16:
print "Id number is",line[5:-2]
ser.close()
I’m using Pyserial to connect to an ID card reader and would like to have continuous polling. If I print everything, I notice that each timeout causes the readline to store an empty string. The above code ameliorates the problem of an ugly/infinite output, but I’m worried about memory usage. Since I’m reusing “line”, I presume there’s no issue there, but is there a problem with unlimited polling to begin with?
Thank you
It looks fine – you should not waste memory in that loop, as it does not keep references to past lines.
Setting a watch on the process to see whether memory consumption is growing over a day or two would not hurt you – but I’d not worry.
Let’s suppose you are running this on an old machinne with 512MB RAM, and only 200MB left for the Python process – and that the timeout to readline takes one second, and that each empty string object takes up some 64 bytes in memory – you would be out of RAM in about 37 days.