Pynput-操控你的鍵盤和鼠標!
此文轉(zhuǎn)載:https://pumpkin8.com/101.html
前言:Pynput是一個可以操控鍵盤和鼠標進行一些自動化操作的一個Python庫,合理利用可以達到提升工作效率的效果。
1.安裝Pynput庫
按下Win+R鍵輸入cmd打開命令提示符,輸入指令以安裝Pynput庫。
pip install pynput
2.使用文檔
(1)鼠標部分
引入控制鼠標的模塊:
from pynput import mouse
獲取鼠標的控制對象:
m=mouse.Controller()
獲取鼠標當前坐標:
print(m.position)
改變鼠標位置:
m.position = (100, 100)
以當前鼠標位置為原點進行偏移:
m.move(10, 10)
以下代碼若想切換為右鍵將left切換為right即可
按下鼠標左鍵:
m.press(mouse.Button.left)
釋放鼠標左鍵:
m.release(mouse.Button.left)
注意!按下左鍵一定要釋放左鍵才能進行下一步操作,可以搭配Time庫進行長按操作,單擊操作不建議使用此代碼。
單擊鼠標左鍵(雙擊把1改成2即可):
m.click(mouse.Button.left, 1)
滾輪向上:
m.scroll(0, 100)
滾輪向下:
m.scroll(0,-100)
(2)鍵盤部分
引入控制鍵盤模塊:
from pynput import keyboard
獲得鍵盤的控制對象:
kb=keyboard.Controller()
獲取按鍵:
獲取特殊按鍵,可以通過 keyboard.Key找到
shift keyboard.Key.shift
ctrl keyboard.Key.ctrl
alt keyboard.Key.alt
獲取普通按鍵
可以通過keyboard.KeyCode.from_char’獲取,特殊按鍵不可以,使用時會報ArgumentError`
兩者都可以使用keyboard.KeyCode.from_vk通過鍵盤的映射碼來獲取
鍵位碼表
按下A鍵:
kb.press("a")
釋放A鍵:
kb.release("a")
同時按下Shift+A鍵:
with kb.pressed(keyboard.Key.shift):
? ?kb.press('a')
? ?kb.release('a')
輸出”hello,word”:
kb.type('hello word.')
(3)鍵盤鼠標監(jiān)聽:
鼠標的:
from pynput import mouse
# 鼠標move監(jiān)聽
def on_move(x, y):
? ?print(f'移動至: ({x}, {y})')
# 鼠標click監(jiān)聽
def on_click(x, y, button, pressed):
? ?print(f'在此坐標點擊: ({x}, {y})')
? ?print(f'點擊的按鍵: {button}')
? ?print(f'類型: {"Pressed" if pressed else "Release"}')
# 鼠標滾輪scroll監(jiān)聽
def on_scroll(x, y, dx, dy):
? ?print(f'滾輪變化時的坐標: ({x}, {y})')
? ?print(f'滾輪變化了: ({dx}, {dy})')
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
? ?listener.join()
鍵盤的:
from pynput import keyboard
def on_press(key):
? ?"""按下按鍵時執(zhí)行。"""
? ?try:
? ? ? ?print('alphanumeric key {0} pressed'.format(
? ? ? ? ? ?key.char))
? ?except AttributeError:
? ? ? ?print('special key {0} pressed'.format(
? ? ? ? ? ?key))
? #通過屬性判斷按鍵類型。
def on_release(key):
? ?"""松開按鍵時執(zhí)行。"""
? ?print('{0} released'.format(
? ? ? ?key))
? ?if key == keyboard.Key.esc:
? ? ? # Stop listener
? ? ? ?return False
# Collect events until released
with keyboard.Listener(
? ? ? ?on_press=on_press,
? ? ? ?on_release=on_release) as listener:
? ?listener.join()
文章到此結(jié)束,如果有錯誤的地方,歡迎評論指出。
作者博客同步發(fā)出,求求各位觀眾老爺支持支持。
https://pumpkin8.com/101.html