循环直到按下特定键

Looping until a specific key is pressed

我试图制作一个 while 循环,当按下特定键时它会停止 运行。问题是循环无限运行。我的循环:

import time
import keyboard

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

我正在使用 keyboard 模块。我的循环有什么问题,我该如何解决? (在这种情况下,我真的不想使用 Repeat-until or equivalent loop in Python 东西。)

while 循环中不需要括号,这是我的代码:

import keyboard

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

这是一个有效的解决方案:

import keyboard
import time
import threading

class main:
    def __init__(self):
        # Create a run variable
        self.run = True

        # Start main thread and the break thread
        self.mainThread = threading.Thread(target=self.main)
        self.breakThread = threading.Thread(target=self.breakThread)

        self.mainThread.start()
        self.breakThread.start()

    def breakThread(self):
        print('Break thread runs')
        # Check if run = True
        while True and self.run == True:
            if keyboard.is_pressed('esc'):
                self.newFunction()

    def main(self):
        print('Main thread runs')
        
        # Also check if run = True   
        while not keyboard.is_pressed('esc') and self.run == True:
            print('test')
            time.sleep(2)
            
            # Break like this
            if keyboard.is_pressed('esc'):
                break

            print('test')
            time.sleep(2)

    def newFunction(self):
        self.run = False
        print('You are in the new function!')

program = main()