keyboard events - Python cross-platform listening for keypresses? -
this question has answer here:
- python read single character user 17 answers
i need listen keypresses in python terminal program without pausing execution raw_input
. i've seen people use few windows specific ways of listening keystrokes , i've seen people use large modules tkinter , pygame want avoid.
is there lightweight module out there cross platform (at least ubuntu, windows, mac)? or there way use event system tkinter, pygame, etc...?
if not, how should approach tackling this? first thought redirect stdin process , keep checking see if contains 1 of event keys.
edit
thank @unutbu taking time mark question 3 years old , answered duplicate of question answers not apply question because asked non-blocking solution.
i don't know of cross-platform lightweight module listens keypresses. here's suggestion in case want implement simple:
check out question on getting single keypress @ time in python faq. experiment bit blocking reads sys.stdin
, threading
. may work on unix. on windows, can use msvcrt.kbhit
.
combining keypress recipe python faq , msvcrt
module, resulting kbhit
function go this:
try: msvcrt import kbhit except importerror: import termios, fcntl, sys, os def kbhit(): fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.icanon & ~termios.echo termios.tcsetattr(fd, termios.tcsanow, newattr) oldflags = fcntl.fcntl(fd, fcntl.f_getfl) fcntl.fcntl(fd, fcntl.f_setfl, oldflags | os.o_nonblock) try: while true: try: c = sys.stdin.read(1) return true except ioerror: return false finally: termios.tcsetattr(fd, termios.tcsaflush, oldterm) fcntl.fcntl(fd, fcntl.f_setfl, oldflags)
Comments
Post a Comment