在 python 中停止 While 循环执行

Stop While Loop mid execution in python

我试图在执行过程中停止 while 循环,如果我在执行过程中反转 'runWhile' 的值,它会一直等到它结束。

问题:我需要它在我按下键盘上的 f10 时立即停止

from pynput import keyboard
import threading
import datetime, time

def exec():
    while runWhile:
        print("There I go")
        time.sleep(3)
        print("I overtaken")
        time.sleep(3)
        print("You cant stop me until I finish")
        
def on_press(key):
    global runWhile # inform function to assign (`=`) to external/global `running` instead of creating local `running`

    if key == keyboard.Key.f5:
        runWhile = True
        t = threading.Thread(target=exec)
        t.start()
    if key == keyboard.Key.f10:
        # to stop loop in thread
        print("loading STOPPED", datetime.datetime.now()) #, end='\r')
        runWhile = False

    if key == keyboard.Key.f11:
        # stop listener
        print("listener TERMINATED", datetime.datetime.now()) #, end='\r')
        return False
        
        
#--- main ---
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

Im using pynput, docs here

这是我做的一个解决方案。我创建了自己的延迟函数如下:

def delay(amount): #delay time in seconds
    for i in range(int(amount*60)):
        time.sleep(0.01)
        if runWhile == False:
            return True
            break

您可以将延迟 (3) 替换为

if delay(3):
    break

这将等待 3 秒,但是如果在此期间 runWhile 为假,它将跳出循环。您的代码如下所示:

from pynput import keyboard
import threading
import datetime, time

def delay(amount): #delay time in seconds
    for i in range(int(amount*60)):
      time.sleep(0.01)
      if runWhile == False:
        return True
        break

def exec():
    while runWhile:
        print("There I go")
        if delay(3):
          break
        print("I overtaken")
        if delay(3):
          break
        print("You cant stop me until I finish")
        
def on_press(key):
    global runWhile # inform function to assign (`=`) to external/global `running` instead of creating local `running`

    if key == keyboard.Key.f5:
        runWhile = True
        t = threading.Thread(target=exec)
        t.start()
    if key == keyboard.Key.f10:
        # to stop loop in thread
        print("loading STOPPED", datetime.datetime.now()) #, end='\r')
        runWhile = False

    if key == keyboard.Key.f11:
        # stop listener
        print("listener TERMINATED", datetime.datetime.now()) #, end='\r')
        return False
        
        
#--- main ---
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()