【发布时间】: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()
【问题讨论】:
-
如果你的意思是终止整个程序,调用 sys.exit() 就够了吗?
-
@thesturggler 是的,我想这会起作用,但如果我想终止程序,我可以返回 false,就像在“f11”选项中一样。我只想停止特定的 while 循环,而不是侦听器/整个程序。
标签: python loops while-loop wait pynput