首页 > 解决方案 > 听按键需要很大的处理器速度

问题描述

当我使用下面的代码时,python 占用了 30% 的处理器速度。有没有办法避免这种情况?

import keyboard  
while True:  
    try:  
        if keyboard.is_pressed('ctrl+shift+m'):  
            print('You Pressed ctrl+shift+m')
            break  
    except:
        break 

标签: python

解决方案


is_pressed总是返回TrueFalse立即返回。它不会等待按键被按下或释放。因此,您的代码一直处于循环中,尽可能频繁地检查这些键是否被按下。而不是is_pressed,使用wait

import keyboard
keyboard.wait('ctrl+shift+m')
print('You Pressed ctrl+shift+m')

推荐阅读