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

How do I break out of the loop at anytime with a keypress

我在 Windows 10,VSCode,Python 3.9

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

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

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, 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, 864, 0.5)

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

如果你想在 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, 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, 864, 0.5)
except KeyboardInterrupt:
    sys.exit()

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

退出程序

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

如评论中所述,线程化是一种不错的方式:

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