[英]Why is KeyboardInterrupt not working for Python pyautogui script? Alternative way to exit program/loop?
[英]How to exit a Python program or loop via keybind or macro? Keyboardinterrupt not working
我正在嘗試完成一個簡單的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)來做這樣的事情。 我覺得我在解決方案中跳舞。 任何和所有幫助將不勝感激! 提前致謝。
如果我理解正確,則希望能夠通過按鍵盤上的某個鍵來停止程序。
為了使您創建一個線程,如果您按下相應的鍵,它將在后台簽入。
一個小例子:
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
希望它的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.