[英]How to make python script more efficient while loop
I have a simple python script that listens to my keypress and executes a command upon keypress.我有一个简单的 python 脚本,它监听我的按键并在按键时执行命令。 In my code, I have an infinite while loop which is pretty harsh on the performance of my computer.
在我的代码中,我有一个无限的 while 循环,这对我的计算机的性能非常苛刻。 I'm wondering what's a better way to achieve the same behavior with less impact on the performance.
我想知道在对性能的影响较小的情况下实现相同行为的更好方法是什么。 The objective is to print a text which says
目标是打印一个文本,上面写着
You Pressed A Key!
你按了一个键!
Every time I press a certain key, in this case, 'h', I want to be able to press h multiple times not just once hence the while loop.每次我按下某个键时,在这种情况下,'h',我希望能够多次按下 h 而不仅仅是一次,因此是 while 循环。
import keyboard
while True:
if keyboard.is_pressed('h'):
print('You Pressed A Key!')
You may want to make the process sleep for a while using:您可能希望使用以下方法使进程休眠一段时间:
import time导入时间
time.sleep(number_of_seconds) time.sleep(number_of_seconds)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.