How to catch "Python Not Responding" exception? - python

I used this function below to keep the Python program pressing 'enter" over and over again, but when I click with the mouse, a window appears with "Python Not Responding" and then I have to close the program, so my question is; is there any way for me to catch that with Python?
Code:
def stop():
pyautogui.FAILSAFE = False
while True:
pyautogui.press('enter')
Thanks in advance!

You cannot catch your program crashing as if it were an exception. What you can do in add a delay between sending each key press:
import time
def stop():
pyautogui.FAILSAFE = False
while True:
pyautogui.press('enter')
time.sleep(0.1)

Related

Keyboard macro press X each few secons while i press other keys

I'm playing a game that i need to press X each 1 sec, while i press other keyboard keys, but my hands are responding to pain
first i tried to do it on javascript:
const robot = require("robotjs");
function Sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function Main() {
console.log("running...");
await Sleep(2500);
PressTogether();
await Main();
}
function PressTogether() {
robot.keyTap("x");
}
Main();
also on python
import pyautogui
import time
print("hey")
while True:
time.sleep(2.5)
pyautogui.press("x")
time.sleep(2.5)
pyautogui.press("x")
print("bye")
Both are pressing the X each 2.5 seconds, but both got the same problem
it freezes my keyboard, i cant press any other key
why this is happen? how to fix?
Your keyboard doesn't react since by using sleep, you suspend the whole thread. It then is not able to do anything except blocking execution.
After sleeping for 2.5 seconds you just do sending out a keyboard action (pressing x key).
Then you are suspending your thread again.
Doing so, your process feels like being frozen because you effectively block your only one main thread most of the time.
You can overcome to that behavior by introducing another thread, which is responsible for your keyboard inputs taking them from stdin.
Here is one approach for python
import pyautogui
from time import sleep
from threading import Thread
from pynput.keyboard import Key, Listener
# a custom function that blocks for a moment and simulates key press
def akp_task():
print("hey")
while True:
time.sleep(2.5)
pyautogui.press("x")
time.sleep(2.5) #this could be omitted
pyautogui.press("x") #this could be omitted
# another function that handles manual key press inputs
def mkpi_task(key):
print('\nmanual pressed: {0}'.format(key))
if key == Key.delete:
# Stop listener
return False
# create a thread for auto key press
akp_thread = Thread(target=akp_task)
# run the thread
akp_thread.start()
# create another thread for your manual key press inputs
with Listener(on_press = mkpi_task) as listener:
listener.join()
References:
threading
manual key press handling

Why is input() being ignored?

Why is the input() after the if statement not working?
I need some help, the input() after the if statement is supposed to stop the script, however it just continues. If i give it another command, for example print("...") or time.sleep(10) it will execute, it is only the input() that does not work. Any ideas?
Edit: Because it might not be clear what the intention is. When asking for an input after the if statement the script should wait before continuing. This is because I want it to pause after I move the mouse so that it does not keep spamming the keys, but I am able to resume it if needed.
import time
from pynput.keyboard import Key, Controller as KeyController
from pynput.mouse import Controller as MouseController
key = KeyController()
mouse = MouseController()
def f1_toggle():
key.press(Key.f1)
key.release(Key.f1)
def enter_toggle():
key.press(Key.enter)
key.release(Key.enter)
input("Press any key to start:")
time.sleep(5)
while True:
start_position = mouse.position
key.press(Key.ctrl_l)
print("Ctrl pressed")
f1_toggle()
print("F1 toggled")
key.release(Key.ctrl_l)
print("Ctrl released")
time.sleep(1)
enter_toggle()
print("Enter toggled")
time.sleep(.5)
end_position = mouse.position
if start_position != end_position:
input("Press any key to continue ")
You're calling enter_toggle() before you ask for input. This is simulating pressing the Enter key. This is being used as the response to the input() call, so it doesn't wait for the user to enter something manually.
Are you sure the two variables are different?
I don't have pyinput, and I am using python 3.8, but in my computer, the input isn't skipped (I commented the pyinput).
Try this:
try:
input("Press any key to continue ")
except Exception as e:
print(e);
Try to see if this helps and what it prints.

Stop click (python module) from catching/handling KeyboardInterrupt

I have the following code:
import click
#click.command()
def main():
while True:
pass
try:
main()
except KeyboardInterrupt:
print('My own message!')
When I press Ctrl+C to exit the program, I want to print my own message. However, click intercepts the error and this is the output:
^C
Aborted!
How can I stop click from handling the errors?
I think I've solved my problem with this code! Hopefully, it's the correct way to handle my problem.
import click
#click.command()
def main():
while True:
pass
try:
main(standalone_mode=False)
except click.exceptions.Abort:
print('My own message!')

handling unexpected shutdown python

is there any way to catch an exception for an unexpected shutdown of program in python ?
let say I am running a python script in a console then I don't press control+c to stop the program but rather just click the close button of the console is there any way to catch the error before the console close?
like this:
try:
print("hello")
except KeyboardInterrupt:
exit()
except UnexpectedClose:
print("unexpected shutoff")
exit()
thanks in advance
Following the link I put in the comment above already and reading here that forced closing is sending a SIGHUP this modified version writes an output file when the terminal window is closed and the python process is "killed".
Note, I just combined information (as cited) available on SE.
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
signal.signal(signal.SIGHUP, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
with open('kill.txt', 'w') as fpntr:
fpntr.write('killed')
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while True:
time.sleep(1)
print("doing something in a loop ...")
if killer.kill_now:
break
print "End of the program. I was killed gracefully :)"

Python cannot cancel timer thread

I am trying to detect a long press event and cancel it if the button is released before the timer times out, however the timer never gets cancelled and fires if it is a short press or a long one:
from threading import Thread
but_down = Timer(1.5,long_press)
if(but=='down'):
but_down.start()
else:
but_down.cancel()
def long_press():
print('long press')
Your code didn't run for me due to errors, but once I fixed those it worked fine:
This outputs long press after 1.5 seconds:
from threading import Timer
but = "down"
def long_press():
print('long press')
but_down = Timer(1.5,long_press)
if(but=='down'):
but_down.start()
else:
but_down.cancel()
This outputs nothing:
from threading import Timer
but = "up"
def long_press():
print('long press')
but_down = Timer(1.5,long_press)
if(but=='down'):
but_down.start()
else:
but_down.cancel()
I don't know what but is but my guess is that your but=='down' test might be the cause of the error.

Categories