Using Mouse and Keyboard Listeners Together in Python
Asked Answered
P

3

5

I have been using pynput library for monitoring the clicks of the mouse.The only problem I am facing is that the terminal does not terminate on pressing Ctrl+C. I need to use keyboard listener with mouse listener. Here's my code:

import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
f=open('maniac1.txt','a')

inc=1
f.write('<mouse_new>\n')

def on_click(x, y, button, pressed):
    f=open('maniac1.txt','a')
    if button == mouse.Button.left:
        print 'Left'
        f.write('left\n')

    if button == mouse.Button.right:
        print 'right'
        f.write('right\n')
    if button == mouse.Button.middle:
        print 'middle'
        f.write('middle\n')

with mouse.Listener(on_click=on_click,on_scroll=on_scroll) as listener:
    try:
        listener.join()
    except MyException as e:
        print('Done'.format(e.args[0]))

How can i terminate this code after pressing Esc or Ctrl+C?I am using OSX.

Petrel answered 31/8, 2017 at 4:53 Comment(2)
press "option + c"Gobang
I had already mentioned that i have used option+C .It is not working.The program does not terminate. I want to add keyboard listener with the mouse listenerPetrel
E
10

Create an instance keyboard.Listener without "with" keyword so that you can start and stop the listener based on your mouse listener. Check the below code which will stop listening to key-press of f8 after right click by mouse.

import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
#f=open('maniac1.txt','a')

inc=1
#f.write('<mouse_new>\n')
from pynput import keyboard

def on_functionf8(key):
    if (key==keyboard.Key.f8):
        print('f8 is pressed')


key_listener = keyboard.Listener(on_release=on_functionf8)
key_listener.start()


def on_click(x, y, button, pressed):
    f=open('maniac1.txt','a')
    if button == mouse.Button.left:
        print ('Left')
        #f.write('left\n')

    if button == mouse.Button.right:
        key_listener.stop()
        print ('right')
        #f.write('right\n')
    if button == mouse.Button.middle:
        print ('middle')
        #f.write('middle\n')

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        print('Done'.format(e.args[0]))

run the program and press f8 and you will see 'f8 is pressed' on the terminal. But right click and press f8. You wont see anything printed as we stopped the keyboard listener on right click of mouse.

for mac:

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))



key_listener = keyboard.Listener(on_release=on_press)

only few keys like cmd, alt are listened on mac by default.

Effective answered 1/9, 2017 at 7:4 Comment(4)
Nope..It doesnt show F8 is pressed.I tried pressing F8 after the right click too.It only displays the mouse clicks.i.e Left/Right/Middle.Petrel
By default mac protects from keyloggers, doesn't let you listen to keypresses except few keys like cmd,alt etc.. That is different issue altogether. If you want to check the functionality, print every key and try pressing cmd or alt. Added this to the answer. Please check.Effective
Yes,You are right.It only listens to Special Keys like 'Shift', 'cntrl ','command.' But I want the OS to listen to other alphanumeric keys too. How can I make this happen?Petrel
Making that happen on Mac is a tough task considering the restrictions applied by apple. There are many open issues for this. If you think I have answered your actual question of combining keyboard and mouse control.., please accept this as answerEffective
E
7

This code using mouse and keyboard listeners together.

from pynput.keyboard import Listener  as KeyboardListener
from pynput.mouse    import Listener  as MouseListener
from pynput.keyboard import Key
import logging

logging.basicConfig(filename=("log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')

def end_rec(key):
    logging.info(str(key))

def on_press(key):
    logging.info(str(key))

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

def on_click(x, y, button, pressed):
    if pressed:
        logging.info('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))

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


with MouseListener(on_click=on_click, on_scroll=on_scroll) as listener:
    with KeyboardListener(on_press=on_press) as listener:
        listener.join()
Europe answered 8/3, 2019 at 7:36 Comment(2)
Explain what your answer does so that other user's can undestandHelldiver
The main idea is indented "with". I reproduced the concept in my code and it worked perfectly. The user @Europe answered exactly what was asked: "how to use Mouse and Keyboard Listeners Together in Python".Poulenc
T
7

I've just finished the same thing a few hours ago, here is what I wrote.

First add another keyboard listener:

# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, \
        mouse.Listener(on_click=on_click) as m_listener:
    k_listener.join()
    m_listener.join()

Then add the on_release function:

def on_release(key):
    if key == keyboard.Key.esc:
        # Stop listeners
        m_listener.stop()
        return False

Then if you press Esc this code will be terminate.

For OSX you need to run python with sudo or it won't work fine.

Tagmemics answered 6/12, 2019 at 15:27 Comment(2)
Very good! This is the only code that works fine! No wonder that you didn't get any upvote until mine! (Really good answers are not supported in here!)Segovia
@Segovia i am tottaly agree with you thank to wowo878787Cointreau

© 2022 - 2024 — McMap. All rights reserved.