Reputation: 69
I created a short script to help out with work today. I set it up so as long as there isn't an interrupt, my loop continues, but the second I press ctrl+c, the script should stop. It stops if I'm clicked in my editor or python shell, but if I'm in the window I want to use automation for, it does not stop. Can someone help me figure this out?
Here is the code, including modifications suggested by Hanz:
import pyautogui
import sys
import time
#Timer to get setup
for i in range(7,0,-1):
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
time.sleep(1)
# i move the loop section
import keyboard
# Defining a interrupter
def interrupter():
raise KeyboardInterrupt("[i] Interrupted!")
# Or use exit
# exit()
# assigning the function to your code
keyboard.add_hotkey("ctrl+shift+c",interrupter)
#Loop
try:
while True:
pyautogui.click()
time.sleep(0.33)
pyautogui.hotkey("enter")
except KeyboardInterrupt:
exit()
Error I am receiving based modifications:
7 6 5 4 3 2 1 Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\myname\AppData\Local\Programs\Thonny\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\myname\AppData\Local\Programs\Thonny\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\myname\AppData\Roaming\Python\Python37\site-packages\keyboard\_generic.py", line 58, in process
if self.pre_process_event(event):
File "C:\Users\myname\AppData\Roaming\Python\Python37\site-packages\keyboard\__init__.py", line 218, in pre_process_event
callback(event)
File "C:\Users\myname\AppData\Roaming\Python\Python37\site-packages\keyboard\__init__.py", line 649, in <lambda>
handler = lambda e: (event_type == KEY_DOWN and e.event_type == KEY_UP and e.scan_code in _logically_pressed_keys) or (event_type == e.event_type and callback())
File "C:\Users\myname\Coding\Pythoon\mousecontroller.py", line 17, in interrupter
raise KeyboardInterrupt("[i] Interrupted!")
KeyboardInterrupt: [i] Interrupted!
Upvotes: 0
Views: 426
Reputation: 445
You can use another Python Package, keyboard
and mouse
.
Installation: pip3 install keyboard mouse
Usage:
import sys
import time
#Timer to get setup
for i in range(7,0,-1):
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
time.sleep(1)
# i move the loop section
import keyboard, mouse
#Loop
while keyboard.is_pressed("ctrl+shift+c") == False:
mouse.click()
time.sleep(0.33)
keyboard.send("enter")
Upvotes: 1