python - 检查键盘输入使用过多的 cpu 使用率,我的代码有问题吗?
问题描述
我正在制作一个简单的音乐播放器,因此当我在全屏应用程序中时可以暂停音乐。该代码运行良好,但我注意到它使用了大约 15% 的 cpu 使用率。我只是想知道我的代码是否做错了什么。
import keyboard
listedSongs = []
currentSong = "idk"
while True:
if keyboard.is_pressed('alt+k'):
i = 1
paused = False
elif keyboard.is_pressed('alt+q'):
break
elif keyboard.is_pressed('alt+s'):
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
任何帮助,将不胜感激 :)
解决方案
它消耗这么多资源的最大原因是:
while True:
本质上,程序永远不会停止等待任何东西。它不断地检查,一遍又一遍,看看键盘上的按钮是否被按下。一种更好的方法,这在计算机上的成本要低得多,是分配一个“回调”,以便在您按下所需的键时调用,并让程序在按键之间休眠。该keyboard
库提供此功能:
import keyboard
import time
listedSongs = []
currentSong = "idk"
exit = False # make a loop control variable
def alt_k():
i = 1
paused = False
def alt_q():
exit = True
def alt_s():
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
# assign hooks to the keyboard
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
keyboard.on_press_key("alt+q", alt_q)
keyboard.on_press_key("alt+s", alt_s)
# main loop
while not exit:
keyboard.wait() # "block" for input (essentially, do nothing until a key is pressed and yield CPU resources to anything else that wants them)
推荐阅读
- vb.net - System.Data.OleDb.OleDbException 没有为一个或多个必需参数指定值?
- jmeter - 如何在 Jmeter 中增加 Content-Length 分隔的消息正文
- python - 将子进程的 Unicode 输出打印到 Windows 上的终端
- javascript - Javascript忽略if语句
- android - 强制用户首先登录还是在他想付款时登录?
- python - Keras:ValueError:检查输入时出错
- angular - 在 Angular 中将数组项绑定到 [(value)]
- javascript - JS 如何在不知道名字的情况下使用 Object 变量?
- powershell - 使用 Powershell 的嵌套哈希表中的 Foreach 循环与 if/elseif
- sql - XML 到 SQL 问题