在python中轮询键盘(检测按键)如何从控制台python应用程序轮询键盘?具体来说,我想在许多其他I / O活动(套接字选择,串行端口访问等)中做类似的事情: while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something在Windows上执行此操作的正确pythonic方法是什么?此外,Linux的可移植性也不错,但并不是必需的。
3 回答

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
使用curses模块的解决方案。打印与按下的每个键对应的数值:
import cursesdef main(stdscr): # do not wait for input when calling getch stdscr.nodelay(1) while True: # get keyboard input, returns -1 if none available c = stdscr.getch() if c != -1: # print numeric value stdscr.addstr(str(c) + ' ') stdscr.refresh() # return curser to start position stdscr.move(0, 0)if __name__ == '__main__': curses.wrapper(main)
添加回答
举报
0/150
提交
取消