You are not logged in.
does anyone how to write a simple program in python that listens to keyboard events and then prints them back to the user from a command line?
Im not looking for code that requires a return key, just somethign that prints out a button when it is pressed.
any help is greatly appreciated,
Thanks.
Offline
I think you're looking for GNU readline... here's a hacked version which compiles into apython module:
http://www.eblong.com/zarf/zymb/readline.c
Offline
wow, i didnt think it would be this complicated.
my intention is to use it in a state machine.
Im writing a quiz that runs from the command line, i would like to change the verbosity by using the arrow keys on the keyboard (up and down).
and i would like to cycle forward and back through the questions by using the forward and back arrows.
would you still suggest using the readline.c module for this?
Offline
you could alway rely on pygame, but i guess it would be a little bit to bloated for your usage.
Offline
thanks cmp, that could work using something like this -
for event in pygame.event.get():
...
but im curious if there are any other ways
Offline
You can put your terminal in noncanonical mode.
import termios, sys, os
def getkey():
term = open("/dev/tty", "r")
fd = term.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] &= ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, new)
c = None
try:
c = os.read(fd, 1)
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, old)
term.close()
return c
if __name__ == '__main__':
print 'type something'
s = ''
while 1:
c = getkey()
if c == 'n':
break
print 'got', c
s = s + c
print s
Offline
You can put your terminal in noncanonical mode.
Nice! I didn't even know python had a terminal io module... good call
Offline
Thanks for the suggestion juergen,
It works really well for any event a->z, 0->9 and a few special characters, but it doesnt seem to work well with arrow keys. I checked abunch of docs on the module, but couldnt find anything
Any suggestions to get this to work with arrow keys?
Offline
try the curses module?
Offline
considered using the curses module, in all honesty, if i was to rewrite the code i would do it in curses.
the non-canonical mode works really well, all i need is for it to pick up arrow keys
Offline
the non-canonical mode works really well, all i need is for it to pick up arrow keys
To make your code working on different terminal types this would require parsing the terminfo database. Better go with curses before reinventing the wheel.
Offline