您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么用Python寫個摸魚監控進程”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么用Python寫個摸魚監控進程”吧!
如果公司偷偷在我們的電腦上運行了一個后臺進程,來監控我們的鍵盤事件,最簡單的 python 寫法大致是這樣的:
from pynput import keyboard def on_press(key): print(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join()
隨意敲擊鍵盤,你就會從控制臺看到這樣的輸出:
代碼內容就是兩個方法,一個是監聽按鍵事件,另一個是監聽退出事件——敲擊 ESC 按鍵后釋放就退出了。
如果還要監聽鼠標事件,那么上這段代碼就行了:
from pynput import mouse def on_click(x, y, button, pressed): if button == mouse.Button.left: print('left was pressed!') elif button == mouse.Button.right: print('right was pressed!') return False else: print('mid was pressed!') # 定義鼠標監聽線程 with mouse.Listener(on_click=on_click) as listener: listener.join()
這段代碼主要是監聽鼠標的左右鍵點擊操作,運行之后操作鼠標,就可以看到控制臺打印如下結果:
細心的你一定會發現,每次點擊事件,都打印了兩次。這是因為按下和松開都會觸發鼠標事件。
鍵盤事件和鼠標事件都有了,是時候將二者結合起來,把用戶的操作記錄到日志了。這里我們用 loguru 來記錄日志,這個 python 模塊我們之前的文章也講過。
整個代碼如下:
from pynput import keyboard, mouse from loguru import logger from threading import Thread # 定義日志文件 logger.add('moyu.log') def on_press(key): logger.debug(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False # 定義鍵盤監聽線程 def press_thread(): with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join() def on_click(x, y, button, pressed): if button == mouse.Button.left: logger.debug('left was pressed!') elif button == mouse.Button.right: logger.debug('right was pressed!') else: return False # 定義鼠標監聽線程 def click_thread(): with mouse.Listener(on_click=on_click) as listener: listener.join() if __name__ == '__main__': # 起兩個線程分別監控鍵盤和鼠標 t1 = Thread(target=press_thread()) t2 = Thread(target=click_thread()) t1.start() t2.start()
運行之后,你就可以在同級目錄下的日志文件中,看到這樣的內容了:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: 閑歡 """ from pynput import keyboard, mouse from loguru import logger from threading import Thread # 定義日志文件 logger.add('moyu.log') def on_press(key): logger.debug(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False # 定義鍵盤監聽線程 def press_thread(): with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join() def on_click(x, y, button, pressed): if button == mouse.Button.left: logger.debug('left was pressed!') elif button == mouse.Button.right: logger.debug('right was pressed!') return False else: logger.debug('mid was pressed!') # 定義鼠標監聽線程 def click_thread(): with mouse.Listener(on_click=on_click) as listener: listener.join() if __name__ == '__main__': # 起兩個線程分別監控鍵盤和鼠標 t1 = Thread(target=press_thread()) t2 = Thread(target=click_thread()) t1.start() t2.start()
到此,相信大家對“怎么用Python寫個摸魚監控進程”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。