在python中轮询键盘(检测按键)

2024-04-28 05:53:14 发布

您现在位置: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的可移植性也不错,尽管它不是必需的。


Tags: to端口应用程序if键盘pythonic事情do
3条回答

import sys
import select

def heardEnter():
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            return True
    return False

使用curses模块的解决方案。打印与每个按键对应的数值:

import curses

def 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)

标准方法是使用select模块。

但是,这在Windows上不起作用。为此,可以使用msvcrt模块的键盘轮询。

通常,这是通过多个线程完成的——每个设备一个被“监视”,外加可能需要被设备中断的后台进程。

相关问题 更多 >