Search code examples
python-3.xpyautoguipynput

Stop mouse event when pressing key


My code uses mouse events to send messages but I have no idea how to stop using an f1 key. I didn't find a stop () method as in Listener () in Events ().

import pynput
import pyautogui
import time
from pynput import mouse
from pynput import keyboard


running = True
mouse_event = mouse.Events()
def on_press(key):
    global running
    if key == keyboard.Key.f1:
        running = False
        print('end')
        return False
def msg():
    mouse_event.start()


    for event in mouse_event:
        if running:
            if isinstance(event,mouse.Events.Click):
                if not event.pressed:
                    pyautogui.typewrite('hello world\n',interval=0.009)
        else:
            time.sleep(1)
            return False
while 1:
    print("Choose the desired option")
    print("1. Message")
    option = int(input("Option:"))
    if option == 1:

            running = True

            with keyboard.Listener(on_press=on_press) as listener:
                if running:
                    msg()
                    
                elif not listener.running:
                    
                    time.sleep(2)
                    break

Is there a way to interrupt a mouse event with the press of a key?

One attempt was to pass the method as on_press to Events () does not work.


Solution

  • I've had to do something similar in the past and I ended up using threading to have one thread listen for the mouse/keyboard input while the other runs my main program.

    import time
    from pynput import keyboard
    from threading import Thread
    
    
    def exit_program():
        def on_press(key):        
            if str(key) == 'Key.f1':
                
                main.status = 'pause'
                user_input = input('Program paused, would you like to continue? (y/n) ')
    
                while user_input != 'y' and user_input != 'n':
                    user_input = input('Incorrect input, try either "y" or "n" ')
    
                if user_input == 'y':
                    main.status = 'run'
    
                elif user_input == 'n':
                    main.status = 'exit'
                    exit()
    
        with keyboard.Listener(on_press=on_press) as listener:
            listener.join()
    
    
    def main():
        main.status = 'run'
    
        while True:
            print('running')
            time.sleep(1)
    
            while main.status == 'pause':
                time.sleep(1)
    
            if main.status == 'exit':
                print('Main program closing')
                break
    
    
    Thread(target=main).start()
    Thread(target=exit_program).start()