python监听鼠标键盘,在Python中一起使用鼠标和键盘侦听器

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值