pynput.mouse Listener do not stop

Question:

Here is my prank code for my friend but I can not stop this program from keyboard when I make executable.

How can I stop this listener from keyboard shortcut. I know it is thread issue.

import sys
import pyautogui
import keyboard
from pynput.mouse import Listener
from threading import Thread

global x,y

def on_move(x, y):
    print ("Mouse moved to ({0}, {1})".format(x, y))

def on_click(x, y, button, pressed):
    try: #FOR AUTO FAIL-SAFE
        if pressed:
            print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
            pyautogui.move(x+100,y+100)
    except:
        pass

def on_scroll(x, y, dx, dy):
    print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

while True:
    if keyboard.is_pressed("q"):
        sys.exit(0)
        break
Asked By: Mr Z

||

Answers:

So here is my fix. I works because I had the same problem:
Insert:

from pynput.keyboard import Key

then:
In on_move(), on_click(), and on_scroll() add:

if key == Key.f10:
    sys.exit()

This will check that when you press f10 (or you can change), the program will exit

You also need to pass key as an argument!

The full updated code is:

import sys
import pyautogui
import keyboard
from pynput.keyboard import Key
from pynput.mouse import Listener
from threading import Thread

global x,y

def on_move(key, x, y):
    print ("Mouse moved to ({0}, {1})".format(x, y))
    if key == Key.f10:
        sys.exit()

def on_click(key, x, y, button, pressed):
    try: #FOR AUTO FAIL-SAFE
        if pressed:
            print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
            pyautogui.move(x+100,y+100)
    except:
        pass
    if key == Key.f10:
        sys.exit()

def on_scroll(key, x, y, dx, dy):
    print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
    if key == Key.f10:
        sys.exit()


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

while True:
    if keyboard.is_pressed("q"):
        sys.exit(0)
        break
Answered By: yoyopi768 yoyopi768

I solved this problem. When mouse position(x,y) on left-top and mid scrolled. Program finishes itself.

def on_scroll(x, y, dx, dy):
    print('Scrolled {0} at {1}'.format(
    'down' if dy < 0 else 'up',
    (x, y,dx,dy)))
    if x<100 and y<100:
        return False
Answered By: Mr Z
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.