User Input in Python Without Pressing Enter

3 May

I got my hands on a barcode scanner and immediately went to writing a python script to manage my laptop inventory. The scanner prints out the value of the code as user input followed by a tab (\t). Windows users tend to click in a text box, scan, press a button and viola! This is cool, but I need to scan several laptops in a row and want it to work like a cash register – why should I have to use the mouse to highlight a text box, scan, press enter, highlight a text box…. Too much work and defeats the purpose of the scanner.

How do you not require the user to hit enter at the command line after they enter text – scan a barcode? The answer is msvcrt. There is a function msvcrt.getch() that reads in each character. Nothing is echoed to the console and it will not wait for enter to be pressed.

My scanner types 13 characters and the 14th is a tab (\t),  so each character is read individually. Not good. I solved this by buffering the characters until a tab (\t) is encountered. I then convert the array to a string and run that string through my database.

No keyboard action required!

The other thing I learned on this is that in python While has an Else.  The while loops took me a few tries to figure out but I am awful at control structures.

Here is my code:

import sqlite3
import sys
import msvcrt

conn = sqlite3.connect(“ini.db”)
cursor=conn.cursor()
d=”
a=[]
i=0
input_char=”

while(d!=’end’):

if (input_char != ‘\t’):
input_char=msvcrt.getch()
a.append(input_char)

else:

d=”.join(a)
d=d.strip(‘\t’)
inputs=”SN”+d
sql=”SELECT term FROM terminals WHERE id='”+inputs+”‘”
for row in cursor.execute(sql):
print row[0]
input_char=”
d=”
a=[]
break

else:
f=open(“My.ini”,”w+”)
f.write(“The Headers for my ini”)
for row in cursor.execute(“SELECT id,term FROM terminals”):
f.write(row[0]+”=”+row[1]+”\n”)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: