pynput --Moniter your keybaord - 图1
© getcodify.com

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

pynput —Moniter your keybaord

1. Mouse

1.1 Mouse Controller

  1. from pynput.mouse import Button, Controller
  2. mouse = Controller()
  3. ## Read pointer position
  4. print('The current pointer position is {0}'.format(
  5. mouse.position))
  6. ## Set pointer position
  7. mouse.position = (10, 20)
  8. print('Now we have moved it to {0}'.format(mouse.position))
  9. ## Move pointer relative to current position
  10. mouse.move(5, -5)
  11. ## Press and release
  12. mouse.press(Button.left)
  13. mouse.release(Button.left)
  14. while True:
  15. mouse.press(Button.left)
  16. ## Double click; this is different from pressing and releasing
  17. ## twice on Mac OSX
  18. mouse.click(Button.left, 2)
  19. ## Scroll two steps down
  20. mouse.scroll(0, 2)

1.2 Mouse Monitor

  1. ##监控鼠标事件
  2. from pynput import mouse
  3. def on_move(x, y ):
  4. print('Pointer moved to {o}'.format(
  5. (x,y)))
  6. def on_click(x, y , button, pressed):
  7. print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
  8. if not pressed:
  9. return False
  10. def on_scroll(x, y ,dx, dy):
  11. print('scrolled {0} at {1}'.format(
  12. 'down' if dy < 0 else 'up',
  13. (x, y)))
  14. while True:
  15. with mouse.Listener( no_move = on_move,on_click = on_click,on_scroll = on_scroll) as listener:
  16. listener.join()

2. Keybaord

2.1 Keyboard Controller

  1. ##键盘输入用法
  2. from pynput.keyboard import Key, Controller
  3. keyboard = Controller()
  4. ##Press and release space
  5. keyboard.press(Key.space)
  6. keyboard.release(Key.space)
  7. keyboard.press(Key.left)
  8. keyboard.release(Key.left)
  9. ##Type a lower case A ;this will work even if no key on the physical keyboard is labelled 'A'
  10. keyboard.press('a')
  11. keyboard.release('a')
  12. ##Type two upper case As
  13. keyboard.press('A')
  14. keyboard.release('A')
  15. ## or
  16. with keyboard .pressed(Key.shift):
  17. keyboard.press('a')
  18. keyboard.release('a')
  19. ##type 'hello world ' using the shortcut type method
  20. keyboard.type('hello world')

2.2 Keyboard Monitor

  1. ##键盘监听
  2. from pynput import keyboard
  3. def on_press(key):
  4. try:
  5. print('alphanumeric key {0} pressed'.format(key.char))
  6. except AttributeError:
  7. print('special key {0} pressed'.format(key))
  8. def on_release(key):
  9. print('{0} released'.format(key))
  10. if key == keyboard.Key.esc:
  11. return False
  12. while True:
  13. with keyboard.Listener(
  14. on_press = on_press,
  15. on_release = on_release) as listener:
  16. listener.join()

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗