python - 听按键需要很大的处理器速度
问题描述
当我使用下面的代码时,python 占用了 30% 的处理器速度。有没有办法避免这种情况?
import keyboard
while True:
try:
if keyboard.is_pressed('ctrl+shift+m'):
print('You Pressed ctrl+shift+m')
break
except:
break
解决方案
is_pressed
总是返回True
或False
立即返回。它不会等待按键被按下或释放。因此,您的代码一直处于循环中,尽可能频繁地检查这些键是否被按下。而不是is_pressed
,使用wait
:
import keyboard
keyboard.wait('ctrl+shift+m')
print('You Pressed ctrl+shift+m')
推荐阅读
- javascript - Angular:通过 ngIf 或切换类隐藏/显示元素?
- oracle - SQL 命令在包中时跳过 where 子句
- python - 条件生成器表达式的意外行为
- php - 在 Laravel 中将 Eloquent 导出到 Excel 时如何包含列标题?
- python - 优化大图的子图 - 比自己优化子图慢
- wordpress - 未应用 WordPress 子主题样式
- java - 2个类需要另一个类首先存在。如何解决这种循环类依赖?
- java - XPathFactory#newInstance() 在 Google App Engine 上迁移到 Java 8 后未能为默认对象模型错误创建 XPathFactory
- javascript - 如何在使用承诺和箭头函数发送响应之前等待异步数据?
- ruby - 如何在 Ruby TK 中使用画布制作可滚动框架?