1 回答
TA贡献1784条经验 获得超8个赞
它消耗这么多资源的最大原因是:
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)
添加回答
举报