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('\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.
解决方案
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('\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.