如何随时通过按键跳出循环

问题描述

我使用的是 Windows 10、VSCode、Python 3.9

我的程序是一个无限循环,可以在屏幕上移动我的鼠标。 目前我的代码允许我在鼠标移动之间退出程序,但不能在鼠标移动之间退出。我希望能够通过按键随时中断。

-ThrottleLimit

这是我在这里的第一个问题,所以如果我的格式有误,请告诉我。此外,如果有人建议让我的代码更漂亮,我会很乐意接受。

解决方法

正如评论中提到的,线程是一个很好的方法:

import threading
import time
import keyboard

def move_mouse(arg):    # simulate a blocking function call,like pyautogui.moveTo()
    print("moving {}".format(arg))
    time.sleep(arg)

def loop_through_moves():
    while True:
        move_mouse(1)
        move_mouse(2)
        move_mouse(3)

t = threading.Thread(target=loop_through_moves)
t.daemon = True
t.start()

while True:
    if keyboard. is_pressed('b'):
        break
,

如果你想在 ctrl-C 上退出,你可以像这样使用 try: except: 调用:

import sys
import time
import pyautogui
import keyboard
pyautogui.FAILSAFE = False
pyautogui.PAUSE = 0
var = 1

try:
    while var == 1:
        if keyboard. is_pressed('b'):
            break
        else:
            pyautogui.moveTo(384,216,0.5)
        
        if keyboard. is_pressed('b'):
            break
        else:
            pyautogui.moveTo(1536,864,0.5)
        
        if keyboard. is_pressed('b'):
            break
        else:
            pyautogui.moveTo(384,0.5)
except KeyboardInterrupt:
    sys.exit()

这种方式应该允许您通过按 ctrl-C AKA `KeyboardInterrupt``

PS:Ctrl-C 应该会自动终止你的程序,但这样做了!