Python control keyboard Mouse: Pynput
Address: Https://pypi.python.org/pypi/pynput
This library allows you to control and monitor input devices.
For each input device, it contains a sub-package to control and monitor the input device:
Introduction to Basic usage:
fromPynput.mouseImportButton, ControllerImportTime Mouse=Controller ()Print(mouse.position) time.sleep (3)Print('The current pointer position is {0}'. Format (mouse.position))#Set pointer positonMouse.position = (277, 645)Print('Now we had moved it to {0}'. Format (mouse.position))#鼠标移动 (x, y) distanceMouse.move (5,-5)Print(mouse.position) mouse.press (button.left) mouse.release (button.left)#Double ClickMouse.click (button.left, 1)#Scroll steps downMouse.scroll (0, 500)
To monitor mouse events:
fromPynputImportMousedefon_move (x, y):Print('Pointer moved to {o}'. Format ((x, y) )defOn_click (x, Y, button, pressed):Print('{0} at {1}'. Format ('Pressed' ifPressedElse 'released', (x, y))) if notpressed:returnFalsedefon_scroll (x, y, dx, dy):Print('scrolled {0} at {1}'. Format (' Down' ifDy < 0Else ' up', (x, y))) whileTrue:with Mouse. Listener (No_move= On_move,on_click = On_click,on_scroll =on_scroll) as Listener:listener.join ()
Keyboard input Usage:
fromPynput.keyboardImportKey, Controllerkeyboard=Controller ()#Press and release spacekeyboard.press (key.space) keyboard.release (key.space)#Type a lower case A; this would work even if no key on the physical keyboard is labelled ' a 'Keyboard.press ('a') Keyboard.release ('a')#Type Upper case asKeyboard.press ('A') Keyboard.release ('A')#orWith keyboard. Pressed (Key.shift): Keyboard.press ('a') Keyboard.release ('a')#type ' Hello World ' using the shortcut type methodKeyboard.type ('Hello World')
Keyboard monitoring:
fromPynputImportkeyboarddefon_press (key):Try: Print('alphanumeric key {0} pressed'. Format (Key.char))exceptAttributeerror:Print('special key {0} pressed'. Format (key)defon_release (key):Print('{0} released'. Format (key)ifKey = =keyboard. Key.esc:returnFalse whileTrue:with Keyboard. Listener (on_press=on_press, On_release=on_release) as Listener:listener.join ()
Python combat ===python Control keyboard Mouse: Pynput