I have a Python script running on a Raspberry Pi that sits waiting for user input and records the input in a SQLite database:
#!/usr/bin/env python
import logging
import db
while True:
barcode = raw_input("Scan ISBN: ")
if ( len(barcode) > 1 ):
logging.info("Recording scanned ISBN: " + barcode)
print "Recording scanned ISBN: " + barcode
db.recordScan(barcode, 1)
That db.recordScan() method looks like this:
# Adds an item to queue
def recordScan(isbn, shop_id):
insert = "INSERT INTO scans ( isbn, shop_id ) VALUES ( ?, ? )"
conn = connect()
conn.cursor().execute(insert, [isbn, shop_id])
conn.commit()
conn.close()
(Note: The whole code repo is available at https://github.com/martinjoiner/bookfetch-scanner-python/ if you wanna see how I'm connecting to the db and such)
My problem is that using a USB barcode scanner (which is effectively just a keyboard input that sends a series of keystrokes followed by the Enter key) it is really easy to input at such a fast rate that the command line seems to get "confused".
For example compare the following results...
When you go slow the script works well and the command looks neat like this:
Scan ISBN: 9780465031467
Recording scanned ISBN: 9780465031467
Scan ISBN: 9780141014593
Recording scanned ISBN: 9780141014593
Scan ISBN:
But when you hammer it hard and go really fast the input prompt kind of gets ahead of itself and the messages printed by the script get written on top of the input prompt:
Recording scanned ISBN: 9780141014593
9780141014593
9780141014593
9780465031467
Recording scanned ISBN: 9780141014593
Scan ISBN: Recording scanned ISBN: 9780141014593
Scan ISBN: Recording scanned ISBN: 9780141014593
Scan ISBN: Recording scanned ISBN: 9780465031467
Scan ISBN: 9780571273188
9780141014593
It sometimes hangs in that position indefinitely, I don't know what it's doing but you can wake it back up again with another input and it carries on as normal although the input before the one it hung on doesn't get recorded which is bad because it makes the whole system unreliable.
My question is: Is this an inevitability that I just have to live with? Will I always be able to out-pace the low-powered Raspberry Pi by hitting it with too many inputs in close succession or is there some faster way of doing this? Can I push the database write operation to another thread or something along those lines? Forgive my ignorance, I am learning.