'Looping until a specific key is pressed [duplicate]

I was trying to make a while loop which would stop running when a specific key is pressed. The problem is that the loop runs infinitely. My loop:

import time
import keyboard

while (not keyboard.is_pressed("esc")):
    print("in loop...")
    time.sleep(2)

I am using the keyboard module. What is wrong with my loop and how can I fix it? (I don't really want to use a Repeat-until or equivalent loop in Python thing in this case.)



Solution 1:[1]

You don't need brackets in while loops, here is my code:

import keyboard

# You need no brackets
while not keyboard.is_pressed('esc'):
    print('test')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom