【问题标题】:Stop While Loop mid execution in python在python中停止While Loop中间执行
【发布时间】:2021-07-09 21:32:50
【问题描述】:

我正在尝试在执行过程中停止 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

based on @furas code

【问题讨论】:

  • 如果你的意思是终止整个程序,调用 sys.exit() 就够了吗?
  • @thesturggler 是的,我想这会起作用,但如果我想终止程序,我可以返回 false,就像在“f11”选项中一样。我只想停止特定的 while 循环,而不是侦听器/整个程序。

标签: python loops while-loop wait pynput


【解决方案1】:

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

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

您可以将 delay(3) 替换为

if delay(3):
    break

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多