由於前一篇文章發文後才發現還沒寫完 ....
逆推使用者意圖,就是要搭配監控才會更完整,這篇將介紹如何快速做出監控鍵盤及滑鼠的範例;後續的文章會推出實戰專題來搭配GUI上的相關變化應用。
實作開始:
pip3 install pynput
In [5]: from pynput.mouse import Button, Controller
In [6]: mouse = Controller()
In [7]: # 獲得目前滑鼠座標
In [8]: print(f"current Mouse Position: {mouse.position}")
Out[8]: current Mouse Position: (1027, 440)
[實戰] 監控滑鼠座標
使用pynput 監控目前的滑鼠是如何被操作的, 時間自訂
# mouse monitoring
from pynput.mouse import Listener
import time, sys
def moveTo(x, y):
print(f"moveTo: ({x}, {y})")
def click(x, y, button, is_press):
print(f"Mouse button: {button} in ({x}, {y}) {'press' if is_press else 'release'}")
def scroll(x1, y1, x2, y2):
if x2:
print(f"scroll from ({x1}, {y1}) into { 'right' if x2 > 0 else 'left'}")
else:
print(f"scroll from ({x1}, {y1}) into { 'buttom' if y2 > 0 else 'upper'}")
def main(duration):
listener = Listener(
on_move=moveTo,
on_click=click,
on_scroll=scroll)
print("Test Start")
listener.start()
time.sleep(duration)
listener.stop()
print("Test Finish")
if __name__ == '__main__':
timer = int(sys.argv[1])
main(timer)
效果如下
[實戰] 監控鍵盤事件
使用listener 的方式去監控鍵盤事件,監控時間一樣是自訂
from pynput.keyboard import Key, Listener
import time, sys
def on_press(key):
print(f"Press: {key.char if hasattr(key, 'char') else key.name}")
def on_release(key):
print(f"release: {key.char if hasattr(key, 'char') else key.name}")
def main(duration):
global listener
listener = Listener(on_press=on_press, on_release=on_release)
print("Test Start")
listener.start()
time.sleep(5)
listener.stop()
print("Test End")
if __name__ == '__main__':
timer = int(sys.argv[1])
main(timer)
效果如下
結論:
使用這個模組就可以輕鬆達到監控滑鼠及鍵盤的行為,同時也可以記錄在檔案中,供後續查驗使用
參考資料: