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

在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的可移植性也不错,但并不是必需的。


德玛西亚99
浏览 1620回答 3
3回答

守着星空守着你

标准方法是使用选择模块。但是,这在Windows上不起作用。为此,您可以使用msvcrt模块的键盘轮询。通常,这是通过多个线程完成的 - 每个设备被“监视”一个加上可能需要被设备中断的后台进程。

慕盖茨4494581

使用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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python