How to exit a Python program or loop via keybind or macro? Keyboardinterrupt not working

2024/10/12 21:23:35

I am trying to complete a simple GUI automation program that merely opens a web page and then clicks on a specific spot on the page every 0.2 seconds until I tell it to stop. I want my code to run and have its loop run infinitely until a keybind I specify breaks the loop (or entire program). I started out with the classic, KeyboardInterrupt, which enables CTRL+C to exit a program. Here is what I thought my final code would look like:

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.')

Everything about the code works, except the fact that I can't exit it once the clicking loop starts. Keyboard interrupt and using CTRL-C to exit do not work at all for this script, for whatever reason.

I merely want to be able to press "escape" (or any other key) to exit the loop (or the program altogether) - just any way to make the loop exit and stop. Right now it runs ad infinitum, but I want a simple keybind macro to be able to stop/break it.

I've tried using getch to keybind the escape key to cause a break, but to no avail:

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

I'm surprised it's been so hard to do this in Python. I've checked out a lot of similar problems across Stackoverflow, but with unsatisfactory answers, and none that solve my problem, unfortunately. I've been able to do things like this in simpler coding languages like AuotHotKeys with ease. I feel like I'm dancing around the solution. Any and all help would be wonderfully appreciated! Thanks in advance.

Answer

If I understood correctly, you want to be able to stop your program by pressing a key on your keyboard.

To make you create a thread that will check in background if you press the key in question.

A little example:

import threading, time
from msvcrt import getchkey = "lol"def thread1():global keylock = threading.Lock()while True:with lock:key = getch()threading.Thread(target = thread1).start() # start the background taskwhile True:time.sleep(1)if key == "the key choosen":# break the loop or quit your program

Hope its help.

https://en.xdnf.cn/q/118155.html

Related Q&A

SKlearn prediction on test dataset with different shape from training dataset shape

Im new to ML and would be grateful for any assistance provided. Ive run a linear regression prediction using test set A and training set A. I saved the linear regression model and would now like to use…

How to eliminate suspicious barcode (like 123456) data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

how to get href link from onclick function in python

I want to get href link of website form onclick function Here is html code in which onclick function call a website <div class="fl"><span class="taLnk" onclick="ta.tr…

Python tkinters entry.get() does not work, how can I fix it? [duplicate]

This question already has answers here:Why is Tkinter Entrys get function returning nothing?(6 answers)Closed 7 years ago.I am building a simple program for university. We have to convert our code to …

Pandas secondary y axis for boxplots

Id like to use a secondary y-axis for some boxplots in pandas, but it doesnt seem available. import numpy as np import pandas as pddata = np.random.random((10, 5)) data[:,-1] += 10 # offset one column…

Fixing Negative Assertion for end of string

I am trying to accept a capture group only if the pattern matches and there is not a specific word before the end of the group. Ive tried a # of approaches and none seem to work, clearly Im not getting…

Two Sorted Arrays, sum of 2 elements equal a certain number

I was wondering if I could get some help. I want to find an algorithm that is THETA(n) or linear time for determining whether 2 numbers in a 2 sorted arrays add up to a certain number.For instance, let…

I cant seem to install numpy

I tried to install numpy, but whenever I start my program, I get these messages.Error importing numpy: you should not try to import numpy fromits source directory; please exit the numpy source tree, an…

Using slices in Python

I use the dataset from UCI repo: http://archive.ics.uci.edu/ml/datasets/Energy+efficiency Then doing next:from pandas import * from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_mode…

Elasticsearch delete_by_query wrong usage

I am using 2 similar ES methods to load and delete documents:result = es.search(index=users_favourite_documents,doc_type=favourite_document,body={"query": {"match": {user: user}}})A…