首页 > 解决方案 > 如何通过键绑定或宏退出 Python 程序或循环?键盘中断不起作用

问题描述

我正在尝试完成一个简单的 GUI 自动化程序,该程序仅打开一个网页,然后每 0.2 秒单击一次页面上的特定位置,直到我告诉它停止。我希望我的代码运行并使其循环无限运行,直到我指定的键绑定中断循环(或整个程序)。我从经典的 KeyboardInterrupt 开始,它可以让 CTRL+C 退出程序。这是我认为我的最终代码的样子:

import webbrowser, pyautogui, time
webbrowser.open('https://example.com/')
print('Press Ctrl-C to quit.')
time.sleep(5)
#pyautogui.moveTo(1061, 881)
try:
    while True:
            time.sleep(0.2)
            pyautogui.click(1061,881)
except KeyboardInterrupt:
    print('\nDone.')

关于代码的一切都有效,除了一旦点击循环开始我就无法退出它。无论出于何种原因,键盘中断和使用 CTRL-C 退出对于此脚本都不起作用。

我只想能够按“escape”(或任何其他键)退出循环(或完全退出程序) - 只是让循环退出和停止的任何方式。现在它无限运行,但我想要一个简单的键绑定宏来停止/破坏它。

我尝试使用 getch 键绑定转义键以导致中断,但无济于事:

import webbrowser, pyautogui, time, msvcrt
webbrowser.open('https://example.com')
print('Press Ctrl-C to quit.')
time.sleep(5)
#pyautogui.moveTo(1061, 881)
try:
    while True:
            time.sleep(0.2)
            pyautogui.click(1061,881)
            if msvcrt.kbhit():
                key = ord(readch())
                if key == 27:
                    break

我很惊讶在 Python 中做到这一点是如此困难。我在 Stackoverflow 上检查了很多类似的问题,但答案并不令人满意,不幸的是,没有一个能解决我的问题。我已经能够轻松地用像 AuotHotKeys 这样更简单的编码语言来做这样的事情。我觉得我正在围绕解决方案跳舞。任何和所有的帮助将不胜感激!提前致谢。

标签: pythonkey-bindingspyautoguigetchkeyboardinterrupt

解决方案


如果我理解正确,您希望能够通过按键盘上的一个键来停止您的程序。

为了让您创建一个线程,如果您按下相关键,该线程将在后台检查。

一个小例子:

import threading, time
from msvcrt import getch

key = "lol"

def thread1():
    global key
    lock = threading.Lock()
    while True:
        with lock:
            key = getch()

threading.Thread(target = thread1).start() # start the background task

while True:
    time.sleep(1)
    if key == "the key choosen":
        # break the loop or quit your program

希望它的帮助。


推荐阅读