Search code examples
pythonwhile-loopraspberry-pibarcode

Python - Loop waiting for input


I have looked around on the StackOverflow forums, unable to find a solution that applies to my specific problem.

I need to write a bit of code, that is continuously checking for user input. I have got a Raspberry Pi with a Barcode Scanner attached to it. I want my Python script to loop, waiting for my Barcode Scanner to bleep something (which will then "type" it in the active window, it's acting like a keyboard). When the barcode scanner 'types' the 8 digit number - I need the Python script to stop - take the input and save it in a variable.

This is the only psuedocode I could come up with:

// Create variable, store an empty string

// Create a while loop
// Within the while loop, continuously check for input. 
// If input has been found, stop the loop and save the input in a variable.

I am terribly sorry I couldn't come up with my own code - I just have no idea where to start.

EDIT: The scanner 'types' the digits out. But does not press ENTER. So I have no idea how I can program around that.


Solution

  • You can use this library on a RaspberryPi: https://pypi.python.org/pypi/readchar

    import readchar
    
    
    inputStr = ""
    
    while len(inputStr) != 8:
        inputStr += str(readchar.readchar())
    
    # Quote: "Save it in variable"
    
    variable = inputStr
    
    # Clean
    inputStr = ""
    

    Or, to shorten everything:

    import readchar
    
    variable = ""
    while len(variable) != 8:
        variable += str(readchar.readchar())