-2

I have a simple python script that listens to my keypress and executes a command upon keypress. In my code, I have an infinite while loop which is pretty harsh on the performance of my computer. 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.

import keyboard

while True:
        if keyboard.is_pressed('h'):
            print('You Pressed A Key!')
  • I think you want something like this: https://stackoverflow.com/a/53210441/2740650 – user2740650 Jan 25 '20 at 02:39
  • I don't think a simple while loop will hinter the performance of your computer. In an average production application there are several demon while loop like this running. – srth12 Jan 25 '20 at 02:41
  • And BTW as you seem to have guessed, we never loop like that (it's called a busy wait). Instead we add callbacks to be notified of some action (in this case a key press). – user2740650 Jan 25 '20 at 02:41
  • @srth12 not sure if you noticed it's a tight loop (it's not event-driven). So it's probably looping a few million times per second. It's most definitely *not* what an average production app does. – user2740650 Jan 25 '20 at 02:44
  • Does this answer your question? [Polling the keyboard (detect a keypress) in python](https://stackoverflow.com/questions/292095/polling-the-keyboard-detect-a-keypress-in-python) –  Jan 25 '20 at 02:55

1 Answers1

0

You may want to make the process sleep for a while using:

import time

time.sleep(number_of_seconds)