inblueswithu
inblueswithu

Reputation: 963

Reading a character in python using readchar package

I'm trying to read a character in python so that to perform an action based on the input. I understood there is no easy way to read key strokes in python with the help of Google. I finally found 'readchar' package which is promising but I was not able to make it work in a simple program. Any help is greatly appreciated.



    import readchar

    def keyprint():
        while True:
            print "Press 'A' to Start the recording"
            print "      'Z' to Stop the recording"
            print "      'Enter' to quit the program..."

            # Read a key
            key = readchar.readkey()
            if(key == 'A'):
                print "Started Recording..."
            elif(key == 'Z'):
                print "Stopped Recording..."
            elif(key == '\r'):
                print "Exiting..."
                break
            else:
                print "Please Use only allowed keys: A, Z, Enter!" 

    if __name__ == "__main__":
        keyprint()

EDIT: Output Error

File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 22, in <module>
  keyprint()
File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 10, in keyprint
  key = readchar.readkey()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar.py", line 20, in readkey
  c1 = getchar()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar_linux.py", line 12, in readchar
  old_settings = termios.tcgetattr(fd)

termios.error: (25, 'Inappropriate ioctl for device')

Thanks, inblueswithu

Upvotes: 2

Views: 8704

Answers (2)

Joe_Evans
Joe_Evans

Reputation: 1

Don't use the word 'key' to put your input in, use something like "k". The Readchar module uses the word 'key' in its routine.

            k = readchar.readkey()
            if(k == 'A'): etc etc

Upvotes: 0

inblueswithu
inblueswithu

Reputation: 963

After discussing this issue on github with the creator of the project - magmax (here), I understood that readchar package works only if you try to run it from a terminal but not from any IDE or other non terminal executions. The error is caused because it tries to get the terminal settings which is non existent in this case.

I have been trying to run it from an Wing IDE. The program works great if you try to run it from a terminal.

P.S: magmax suggested to use readchar.keys.ENTER instead of \r . And suggested to have a look at https://github.com/magmax/python-inquirer & its examples

Upvotes: 3

Related Questions