others - python 实时捕获按键处理( 比如 keypress事件)


# http://code.activestate.com/recipes/134892/


def getch():


 try:


 import termios


 except ImportError:


 # Non-POSIX. Return msvcrt's (Windows') getch.


 import msvcrt


 return msvcrt.getch



 # POSIX system. Create and return a getch that manipulates the tty.


 fd = sys.stdin.fileno()


 old_settings = termios.tcgetattr(fd)


 try:


 tty.setraw(fd)


 ch = sys.stdin.read(1)


 finally:


 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)


 return ch




#!/usr/bin/env python3



import sys


import tty


import time



def main():


 while True:


 time.sleep(1)


 sys.stdout.write(" DEBUG:Before")


 sys.stdout.write(getch())


 sys.stdout.write(" DEBUG:After")



if __name__ =="__main__":


 main()




#!/usr/bin/env python3



import sys


import tty


import time


import threading



key = 'Z'



def main():


 threading.Thread(target=getchThread).start()



 while True:


 time.sleep(1)


 sys.stdout.write(" DEBUG:Before")


 sys.stdout.write(key)


 sys.stdout.write(" DEBUG:After")



def getchThread():


 global key


 lock = threading.Lock()


 while True:


 with lock:


 key = getch()



if __name__ =="__main__":


 main()



有什么建议或者指导?

时间:

这个例子只需要简单的while循环


def process(key):


 if key == 'x':


 exit('exitting')


 else:


 print(key, end="", flush=True)



if __name__ =="__main__":


 while True:


 key = getch()


 process(key)



考虑以下代码:


n = 0


quit = False



def process(key):


 if key == 'x':


 global quit


 quit = True


 exit('exitting')


 elif key == 'n':


 global n


 print(n)


 else:


 print(key, end="", flush=True)



def key_capturing():


 while True:


 process(getch())



if __name__ =="__main__":


 threading.Thread(target=key_capturing).start()


 while not quit:


 n += 1


 time.sleep(0.1)



这将创建全局变量n,并在主线程中将它的增加10倍,同时,key_capturing方法监听按键,当你按键盘上的n时,将打印全局变量n的当前值。

return msvcrt.getch应该是return msvcrt.getch()

...