python pynput鼠标键盘监控(详细)第1部鼠标监控

 本人看完原文,认为很简单,结果花费3天时间才基本了解。由于我现在仅仅用到监听,

所以先写监听。模拟功能本模块也有,稍后补充。

      网上搜索了很多,没有见创新的,基本上是原文档的复制,本人经过摸索,基本校全面。

现总结如下。补充说明不要用os._exit or sys.exit退出,那样的话能是不能鼠标监听的。

如有错误或补充欢迎交流。

    另外除非你一定要用控制台程序,没有界面,否则不建议使用,比较难。你可以用pyqt5或matplotlib中鼠标键盘监控事件。

参考本人另一篇博文matplotlib键盘鼠标事件 https://mp.csdn.net/postedit/84777736

pynput模块: 控制监控鼠标和键盘   2018/8/28

 

-------------------------------------------------------------------------------

1.模块函数

1.mouse: 包含鼠标类的模块

1.1.class Button: 鼠标的键值类

left(左键), right(右键),middle(中间建),unknown(未知键)

 

1.2.class Controller:        向系统发送鼠标事件的控制器

position:             指针当前的位置

move(x, y):           将鼠标移动到指定位置

press(button):        按下鼠标键

release(button):       释放鼠标键

scroll(x, y):            发送滚动事件

click(button, count=1): 在当前位置发送点击事件

button:              按下的鼠标键

count:               点击的次数

 

1.3.class Listener: 鼠标的监听器

Listener(no_move,on_click,on_scroll): 创建一个监听器

no_move:                        鼠标移动调用的方法(参数: x, y)

on_click:  鼠标点击调用的方法(参数: x, y, button, pressed)

on_scroll: 鼠标滚轮滑动调用的方法(参数: x, y , dx, dy)

run():    启动监听器

stop():    停止监听器

wait():    等待监听器就绪

join():    启动并等待线程停止

---------------------------------------------------------------------------

2.keyboard: 包含键盘类的模块

2.1.class Key: 键盘的键值类

alt(Alt),alt_l(左Alt),alt_r(右),ctrl(Ctrl),ctrl_l(左Ctrl),ctrl_r(右Ctrl),shift(Shift), enter(回车),

shift_r(右Shift),space(空格),tab(Tab),caps_lock(大小写),cmd(cmd),backspace(退格),

esc(esc),down(下),up(上),left(左),right(右)end(End),delete(Del),home(Home),insert(Ins),

page_down(PageDown),page_up(PageUp),scroll_lock(ScrlLock), pause(PauseBreak)

,print_screen(PrintScr.)f1-12(F1-12),menu(menu),num_lock(NumLock)

 

2.2.class Controller: 向系统发送键盘事件的控制器

press(key):    按下某个键

key:          按下的键

release(key):   释放某个键

pressed(*args): 使下边的按键均同时按下此键(可以用with打开)

type(str):      将字符串发送

 

2.3.class Listener: 键盘的监听器

 

Listener(on_press, on_release): 创建一个监听器

on_press:   按下某个键时调用的方法(参数为key)

on_release: 释放某个键时调用的方法(参数为key)

run():      启动监听器

stop():     停止监听器

wait():      等待监听器就绪

join():      启动并等待线程停止

-------------------------------------------------------------------------------

3.例

1.标准鼠标监控

from pynput import mouse

 

def on_move(x, y):

    print('Pointer moved to {0}'.format((x, y)))

 

def on_click(x, y, button, pressed):

    print('{0} at {1}'.format(

        'Pressed' if pressed else 'Released',(x, y)))

    if not pressed:

        # Stop listener

        return False

 

def on_scroll(x, y, dx, dy):

    print('Scrolled {0} at {1}'.format(

        'down' if dy < 0 else 'up',(x, y)))

 

# Collect events until released

with mouse.Listener(on_move=on_move,on_click=on_click,

                    on_scroll=on_scroll) as listener:

    listener.join()

------------------------------------------------------------------------------

from pynput import mouse,keyboard

from collections import deque

import threading,time,os,sys

'''

1.说明:

    1.0.tcy shanghai 2018/8/28 测试平台windows7 python3.7 pycharm20182.1

    1.1. 一个鼠标监听器是一个线程。所有的回调将从线程调用。

    1.2. 任何地方调用pynput.mouse.Listener.stop,mouse.Listener.StopException

          或从回调中返回False来停止监听器。



2.用途:
    1.1.本函数主要用作鼠标监听
    1.2.实现鼠标监听暂停,启动,停止;停止和销毁后不能再进行鼠标监听,暂停后可以恢复。
3.技术要点
    1.1.构造2个event,停止和暂停;退出采用回调函数内部return False

以恢复
'''

class MouseClass(threading.Thread):

    def __init__(self, *args, **kwargs):

        super(MouseClass, self).__init__(*args, **kwargs)



        self.mouse_listion=mouse.Listener()

        self.__mouse_pause_flag_=threading.Event()   # 用于暂停鼠标线程的标识

        self.__mouse_pause_flag_.set()               # 鼠标线程不阻塞

        self.__mouse_run_flag_ = threading.Event()   # 用于停止鼠标线程的标识

        self.__mouse_run_flag_.set()                 # 鼠标线程开始启用

        self.__mouse_destroy_flag_=True              #True鼠标监听不退出



    def on_move(self,x, y ):

        print("Pointer moved to {0}  {1}".format((x,y),time.ctime()))

        if not self.__mouse_destroy_flag_:            #false鼠标监听停止

           return False                              
#注意:不要返回True,否则不能够暂停等功能

    def on_click(self,x, y , button, pressed):

        print('{0}at{1} '.format('Pressed' if pressed else 'Released',(x, y)))

        #凸轮键松开鼠标监控停止

        if (not self.__mouse_destroy_flag_) or (not pressed):#false鼠标监听停 
             return False



    def on_scroll(self,x, y ,dx, dy):

        print('Scrolled{0} at {1}'.format( 'down' if dy < 0 else 'up',(x, y)))

        if not self.__mouse_destroy_flag_:                  #false鼠标监听停止

           return False

    def run(self):

        while self.__mouse_run_flag_.is_set() :

            if not self.__mouse_destroy_flag_:

                break

            self.__mouse_pause_flag_.wait()

            with  mouse.Listener( no_move = self.on_move,on_click =         
self.on_click,on_scroll = self.on_scroll) as  listener:

               self.mouse_listion = listener

               self.mouse_listion.join()



def mouse_pause(self):

        self.__mouse_pause_flag_.clear()  # 为False鼠标线程阻塞,暂停鼠标功能

        print('鼠标暂停...;当前线程==>%s ;线程数量==%d\n' % (

               threading.current_thread().name, threading.activeCount()))





    def mouse_resume(self):

        self.__mouse_pause_flag_.set()   # True鼠标线程停止阻塞,开启鼠标功能

        print('鼠标恢复...;当前线程==>%s ;线程数量==%d\n' % (

                threading.current_thread().name, threading.activeCount()))



    def mouse_stop(self):

        self.__mouse_run_flag_.clear()   # 设置为False鼠标线程停止

        self.__mouse_pause_flag_.set()

        print('鼠标停用...;当前线程==>%s ;线程数量==%d\n' %(

                threading.current_thread().name, threading.activeCount()))

    def mouse_destroy(self):

        self.__mouse_destroy_flag_=False   # 鼠标监听停止

        print('鼠标监听停止;当前线程==>%s ;线程数量==%d\n' %(

                threading.current_thread().name, threading.activeCount()))



#测试函数

def mouse_test():



    km=MouseClass()

    print('1.Start runing...')

    km.start()

    time.sleep(5)

    print('2.Mouse pause...')

    km.mouse_pause()

    time.sleep(5)

    print('3.Mouse start....')

    km.mouse_resume()

    time.sleep(5)

    print('4.Mouse stop....')

    # km.mouse_stop()#任选一个停止

    km.mouse_destroy()#任选一个停止

    time.sleep(5)

    print('5.End all program!')

    print('当前线程==>%s ;线程数量==%d\n' %(

           threading.current_thread().name, threading.activeCount()))

mouse_test()



# C:\python37\python.exe C:/Users/Administrator/.PyCharmCE2018.2/config/scratches/test3.py

# 1.Start runing...

# Pressed at (338, 619)

# Released at (338, 619)

# Scrolled down at (338, 619)

# Scrolled down at (338, 620)

# 2.Mouse pause...

# 鼠标暂停...;当前线程==>MainThread ;线程数量==3

#

# Scrolled down at (338, 622)

# Scrolled down at (338, 622)

# Pressed at (338, 622)

# Released at (338, 622)

# 3.Mouse start....

# 鼠标恢复...;当前线程==>MainThread ;线程数量==2

#

# Pressed at (338, 622)

# Released at (338, 622)

# Scrolled down at (338, 622)

# Pressed at (338, 622)

# Released at (338, 622)

# Scrolled down at (338, 622)

# Pressed at (338, 622)

# Released at (338, 622)

# Scrolled down at (338, 622)

# Pressed at (338, 622)

# Released at (338, 622)

# 4.Mouse stop....

# 鼠标监听停止;当前线程==>MainThread ;线程数量==3

#

# Scrolled down at (338, 622)

# 5.End all program!

# 当前线程==>MainThread ;线程数量==1
---------------------------------------------------------------------
from pynput import mouse,keyboard

from collections import deque

import threading,time,os,sys

'''

1.说明:

    1.0.tcy shanghai 2018/8/28 测试平台windows7 python3.7 pycharm20182.1

    1.1. 一个鼠标监听器是一个线程。所有的回调将从线程调用。

    1.2. 任何地方调用pynput.mouse.Listener.stop,mouse.Listener.StopException

          或从回调中返回False来停止监听器。

2.用途:

    1.1.本函数主要用作鼠标监听

    1.2.实现鼠标监听暂停启动停止;停止和销毁后不能再进行鼠标监听,暂停后可 

3.技术要点

    1.1.采用鼠标监听内部的线程挂起,当暂停时鼠标不起左右,恢复后又正常工作。

'''

class MouseClass(threading.Thread):

    def __init__(self, *args, **kwargs):

        super(MouseClass, self).__init__(*args, **kwargs)



        self.mouse_listion=mouse.Listener()

        self.__mouse_run_flag_=True                 # 用于暂停鼠标线程不挂起

        self.__mouse_destroy_flag_=True             #True鼠标监听不退出

    def on_move(self,x, y ):

        print("Pointer moved to {0}  {1}".format((x,y),time.ctime()))

        if not self.__mouse_destroy_flag_:            #false鼠标监听停止

           return False                                                                          #  注意:不要返回True,否则不能够暂停等功能

    def on_click(self,x, y , button, pressed):

        print('{0} at{1}'.format('Pressed' if pressed else 'Released',(x, y)))

        #凸轮键松开鼠标监控停止

        if (not self.__mouse_destroy_flag_) or (not pressed): #false鼠标监听停

           return False



    def on_scroll(self,x, y ,dx, dy):

        print('Scrolled {0} at {1}'.format( 'down' if dy <0 else 'up',(x, y)))

        if not self.__mouse_destroy_flag_:                  #false鼠标监听停止

           return False

    def run(self):

        while 1:

            with  mouse.Listener( no_move = self.on_move,on_click = self.on_click,on_scroll = self.on_scroll,

                                  suppress=not self.__mouse_run_flag_) as  self.mouse_listion:

                self.mouse_listion.join()

                if not self.__mouse_destroy_flag_:

                    break



    def mouse_pause(self):

        self.__mouse_run_flag_ = False

        print('鼠标暂停...;当前线程==>%s ;线程数量==%d\n' % (

               threading.current_thread().name, threading.activeCount()))





    def mouse_resume(self):

        self.__mouse_run_flag_=True

        print('鼠标恢复...;当前线程==>%s ;线程数量==%d\n' % (

                threading.current_thread().name, threading.activeCount()))



    def mouse_destroy(self):

        self.__mouse_destroy_flag_=False   # 鼠标监听停止

        self.__mouse_run_flag_ = True

        print('鼠标监听停止;当前线程==>%s ;线程数量==%d\n' %(

                threading.current_thread().name, threading.activeCount()))



#测试函数

def mouse_test():



    km=MouseClass()

    print('1.Start runing...')

    km.start()

    time.sleep(5)

    print('2.Mouse pause...')

    km.mouse_pause()

    time.sleep(5)

    print('3.Mouse start....')

    km.mouse_resume()

    time.sleep(5)

    print('4.Mouse stop....')

    km.mouse_destroy()#任选一个停止

    time.sleep(5)

    print('5.End all program!')

    print('当前线程==>%s ;线程数量==%d\n' %(

           threading.current_thread().name, threading.activeCount()))



mouse_test()



#输出结果:

# 1.Start runing...

# Pressed at (321, 553) 

# Released at (321, 553) 

# Scrolled down at (321, 553)

# Scrolled down at (320, 556)

# Scrolled down at (320, 556)

# 2.Mouse pause...

# 鼠标暂停...;当前线程==>MainThread ;线程数量==3

'''此时鼠标不起作用''' 

# Scrolled down at (320, 556)

# Scrolled down at (320, 556)

# Pressed at (320, 556) 

# Released at (320, 556) 

# Scrolled down at (320, 556)

# Scrolled down at (320, 556)

'''估计是将队列中的剩余任务输出;参考原函数定义'''

# 3.Mouse start....

# 鼠标恢复...;当前线程==>MainThread ;线程数量==3

'''此时鼠标起作用'''

# Pressed at (320, 556) 

# Released at (320, 556) 

# Scrolled down at (320, 556)

# 4.Mouse stop....

# 鼠标监听停止;当前线程==>MainThread ;线程数量==3

# Scrolled down at (320, 556)

'''将队列中的剩余任务输出;鼠标监听退出,等待主线程完成'''

# 5.End all program!

# 当前线程==>MainThread ;线程数量==1

-------------------------------------------------------------------------------

from pynput import mouse,keyboard
from collections import deque
import threading,time,os,sys
'''
1.
说明:
    1.0.tcy shanghai 2018/8/28 测试平台windows7 python3.7 pycharm20182.1
    1.1. 一个鼠标监听器是一个线程。所有的回调将从线程调用。
    1.2. 任何地方调用pynput.mouse.Listener.stop,或pynput.mouse.Listener.StopException
          或从回调中返回False来停止监听器。
2.用途:
    1.1.本函数主要用作鼠标监听
    1.2.实现鼠标监听暂停,启动,停止;停止和销毁后不能再进行鼠标监听,暂停后可以恢复。
3.技术要点
    1.1.采用 self.mouse_listion.stop()暂停监听
            等价于self.mouse_listion.StopException
    1.2.最好不要用self.mouse_listion.run(),测试出现一些异常;可能我理解不透,欢迎大神补充。
        和上面程序差别在MouseClass.run()函数中。
'''

class MouseClass(threading.Thread):
   
def __init__(self, *args, **kwargs):
       
super(MouseClass, self).__init__(*args, **kwargs)

       
self.mouse_listion=mouse.Listener()
       
self.__mouse_run_flag_=True                 # 用于暂停鼠标线程不挂起
       
self.__mouse_destroy_flag_=True             #True鼠标监听不退出
   
def on_move(self,x, y ):
       
print("Pointer moved to {0}  {1}".format((x,y),time.ctime()))
       
if not self.__mouse_destroy_flag_:            #false鼠标监听停止
          
return False                                                       #注意:不要返回True,否则不能够暂停等功能
   
def on_click(self,x, y , button, pressed):
       
print('{0} at{1}'.format('Pressed' if pressed else 'Released',(x, y)))
       
#凸轮键松开鼠标监控停止
       
if (not self.__mouse_destroy_flag_) or (not pressed): #false鼠标监听停
          
return False

    def
on_scroll(self,x, y ,dx, dy):
       
print('Scrolled {0} at {1}'.format( 'down' if dy <0 else 'up',(x, y)))
       
if not self.__mouse_destroy_flag_:                  #false鼠标监听停止
          
return False
    def
run(self):
       
while 1:
           
with  mouse.Listener( no_move = self.on_move,on_click = self.on_click,on_scroll = self.on_scroll,
                                  )
as  self.mouse_listion:
                
if self.__mouse_run_flag_:
                   
self.mouse_listion.join()
               
else:
                   
self.mouse_listion.stop()          # 暂停监听等价于下条语句
                    # self.mouse_listion.StopException #暂停监听等价于上条语句
               
if not self.__mouse_destroy_flag_:
                   
break

    def
mouse_pause(self):
       
self.__mouse_run_flag_ = False
       
print('鼠标暂停...;当前线程==>%s ;线程数量==%d\n' % (
               threading.current_thread().name, threading.activeCount()))


    
def mouse_resume(self):
       
self.__mouse_run_flag_=True
       
print('鼠标恢复...;当前线程==>%s ;线程数量==%d\n' % (
                threading.current_thread().name, threading.activeCount()))

   
def mouse_destroy(self):
       
self.__mouse_destroy_flag_=False   # 鼠标监听停止
       
self.__mouse_run_flag_ = True
       
print('鼠标监听停止;当前线程==>%s ;线程数量==%d\n' %(
                threading.current_thread().name, threading.activeCount()))


#测试函数
def mouse_test():

    km=MouseClass()
   
print('1.Start runing...')
    km.start()
    time.sleep(
5)
   
print('2.Mouse pause...')
    km.mouse_pause()
    time.sleep(
5)
   
print('3.Mouse start....')
    km.mouse_resume()
    time.sleep(
5)
   
print('4.Mouse stop....')
    km.mouse_destroy()
#任选一个停止
   
time.sleep(5)
   
print('5.End all program!')
   
print('当前线程==>%s ;线程数量==%d\n' %(
           threading.current_thread().name, threading.activeCount()))

mouse_test()


#输出结果:同上例程。

 

你可能感兴趣的:(python pynput鼠标键盘监控(详细)第1部鼠标监控)