在python中轮询键盘(检测按键) [英] Polling the keyboard (detect a keypress) in python

查看:739
本文介绍了在python中轮询键盘(检测按键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从控制台python应用程序轮询键盘?具体来说,我想在很多其他I / O活动(套接字选择,串口访问等)之间做类似的事情:

How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):

   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上正确的python方式是什么?

What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.

推荐答案

标准方法是使用选择模块。

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

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

通常,这是通过多个线程完成的 - 每个设备被监视一个,以及可能需要由设备中断的后台进程。

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

这篇关于在python中轮询键盘(检测按键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆