简体   繁体   English

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

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

I'm on Windows 10, VSCode, Python 3.9我在 Windows 10,VSCode,Python 3.9

My program is an infinite loop that moves my mouse around the screen.我的程序是一个无限循环,可以在屏幕上移动鼠标。 Currently my code allows me to exit the program in between mouse movements, but not mid mouse movement.目前,我的代码允许我在鼠标移动之间退出程序,但不能在鼠标移动中间退出。 I want to be able to break at anytime with a keypress.我希望能够通过按键随时休息。

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)

This is my first question on here so please let me know if my formatting is wrong.这是我在这里的第一个问题,所以如果我的格式错误,请告诉我。 Also if anyone has recommendations to make my code prettier I will gladly accept.此外,如果有人建议让我的代码更漂亮,我会很乐意接受。

As mentioned in comments, threading is a good way to go:正如评论中提到的,线程是 go 的好方法:

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

If you want to exit on ctrl-C you can use a try: except: call like this:如果你想在 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()

This way should allow you to exit the program by pressing ctrl-C AKA `KeyboardInterrupt``这种方式应该允许您通过按ctrl-C AKA `KeyboardInterrupt` 退出程序

PS: Ctrl-C should auto kill your program but this does that! PS: Ctrl-C 应该会自动终止您的程序,但这样做!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM