如何通过键盘绑定或宏退出Python程序或循环?键盘中断无法正常工作

时间:2018-10-11 09:07:48

标签: python key-bindings pyautogui getch keyboardinterrupt

我正在尝试完成一个简单的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退出对于此脚本都不起作用。

我只希望能够按“退出”键(或任何其他键)退出循环(或整个程序),这只是使循环退出和停止的任何方式。现在它可以无限运行,但是我希望一个简单的keybind宏能够停止/破坏它。

我尝试使用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)来做这样的事情。我觉得我在解决方案中跳舞。任何和所有帮助将不胜感激!预先感谢。

1 个答案:

答案 0 :(得分:1)

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

要创建一个线程,如果您按下相应的键,它将在后台签入。

一个小例子:

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

希望它的帮助。