PyUserInput
A module for cross-platform control of the mouse and keyboard in python that is simple to install and use.
Top Related Projects
Quick Overview
PyUserInput is a Python library that provides cross-platform support for simulating user input events such as mouse movements, clicks, and keyboard presses. It aims to offer a unified interface for input simulation across Windows, Mac, and Linux operating systems, making it easier for developers to create automation scripts and tools.
Pros
- Cross-platform compatibility (Windows, Mac, and Linux)
- Simple and intuitive API for simulating mouse and keyboard events
- Supports both Python 2 and Python 3
- Actively maintained with regular updates
Cons
- Limited documentation and examples
- Some platform-specific features may not be available on all operating systems
- Requires additional dependencies on some platforms (e.g., Xlib on Linux)
- May require elevated privileges for certain operations on some systems
Code Examples
- Simulating mouse movement and click:
from pynput.mouse import Controller
mouse = Controller()
mouse.position = (100, 200) # Move mouse to coordinates (100, 200)
mouse.click(Button.left, 1) # Perform a left mouse click
- Simulating keyboard input:
from pynput.keyboard import Controller, Key
keyboard = Controller()
keyboard.type('Hello, World!') # Type a string
keyboard.press(Key.enter) # Press the Enter key
keyboard.release(Key.enter) # Release the Enter key
- Listening for mouse events:
from pynput import mouse
def on_click(x, y, button, pressed):
print(f'Mouse {"pressed" if pressed else "released"} at ({x}, {y})')
with mouse.Listener(on_click=on_click) as listener:
listener.join()
Getting Started
To get started with PyUserInput:
-
Install the library using pip:
pip install pynput
-
Import the necessary modules in your Python script:
from pynput import mouse, keyboard
-
Create controller objects for mouse and keyboard:
mouse_controller = mouse.Controller() keyboard_controller = keyboard.Controller()
-
Use the controller objects to simulate input events:
mouse_controller.move(50, 0) # Move mouse 50 pixels to the right keyboard_controller.type('Hello, PyUserInput!')
Remember to handle exceptions and check for platform-specific requirements when using PyUserInput in your projects.
Competitor Comparisons
Sends virtual input commands
Pros of pynput
- More actively maintained with recent updates
- Better cross-platform support (Windows, macOS, Linux)
- Comprehensive documentation and examples
Cons of pynput
- Slightly more complex API
- May require additional setup on some systems
Code Comparison
PyUserInput:
from pymouse import PyMouse
m = PyMouse()
m.click(x, y, 1, 1) # Click at (x, y)
pynput:
from pynput.mouse import Button, Controller
mouse = Controller()
mouse.position = (x, y)
mouse.click(Button.left)
Summary
pynput offers better cross-platform support and more active maintenance compared to PyUserInput. It provides comprehensive documentation and examples, making it easier for developers to implement various input-related functionalities. However, pynput's API is slightly more complex, which may require a steeper learning curve for beginners.
PyUserInput has a simpler API, making it easier to get started with basic input operations. However, it lacks recent updates and may have limited functionality on certain platforms.
Both libraries allow for simulating mouse and keyboard events, but pynput's more extensive feature set and ongoing development make it a more robust choice for most projects, especially those requiring cross-platform compatibility.
A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.
Pros of pyautogui
- More actively maintained with frequent updates
- Comprehensive documentation and examples
- Cross-platform support (Windows, macOS, Linux)
Cons of pyautogui
- Larger codebase, potentially more complex for simple tasks
- Slower execution for certain operations due to additional features
Code Comparison
PyUserInput:
from pymouse import PyMouse
m = PyMouse()
m.click(x, y, 1)
pyautogui:
import pyautogui
pyautogui.click(x, y)
Additional Notes
PyUserInput focuses on providing a simple interface for mouse and keyboard input, while pyautogui offers a broader range of functionality, including screenshot capabilities and GUI automation tools. PyUserInput may be more suitable for projects requiring basic input simulation, whereas pyautogui is better suited for complex automation tasks and cross-platform compatibility.
Both libraries have their strengths, and the choice between them depends on the specific requirements of your project. PyUserInput's simplicity may be advantageous for lightweight applications, while pyautogui's extensive feature set and active development make it a more versatile choice for larger-scale automation projects.
Hook and simulate global keyboard events on Windows and Linux.
Pros of keyboard
- More active development and maintenance
- Broader feature set, including hotkeys and keyboard hooks
- Cross-platform support (Windows, Linux, macOS)
Cons of keyboard
- Limited to keyboard input only (no mouse support)
- Requires root/admin privileges on some systems
Code comparison
PyUserInput:
from pykeyboard import PyKeyboard
k = PyKeyboard()
k.type_string('Hello, World!')
keyboard:
import keyboard
keyboard.write('Hello, World!')
keyboard.add_hotkey('ctrl+shift+a', print, args=('Hotkey pressed!',))
Key differences
PyUserInput offers both keyboard and mouse input simulation, while keyboard focuses solely on keyboard interactions. keyboard provides more advanced features like hotkeys and keyboard hooks, making it suitable for complex keyboard-based applications.
PyUserInput has a simpler API for basic input simulation, but keyboard offers more flexibility and control over keyboard events. keyboard is also more actively maintained and has better cross-platform support.
However, keyboard may require elevated privileges on some systems, which could be a drawback in certain scenarios. PyUserInput might be preferred for projects that need both keyboard and mouse input simulation in a single package.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
PyUserInput
PyUserInput is a group project so we've moved the project over to a group organization: https://github.com/PyUserInput/PyUserInput . That is now the active development repository and I'll be phasing this one out, so please go there for the latest code and to post new issues. This should be corrected on PyPI in the next version update of PyUserInput.
A module for cross-platform control of the mouse and keyboard in python that is simple to use.
Mouse control should work on Windows, Mac, and X11 (most Linux systems). Scrolling is implemented, but users should be aware that variations may exist between platforms and applications.
Keyboard control works on X11(linux) and Windows systems. Mac control is a work in progress.
Dependencies
Depending on your platform, you will need the following python modules for PyUserInput to function:
- Linux - Xlib
- Mac - Quartz, AppKit
- Windows - pywin32, pyHook
How to get started
After installing PyUserInput, you should have pymouse and pykeyboard modules in your python path. Let's make a mouse and keyboard object:
from pymouse import PyMouse
from pykeyboard import PyKeyboard
m = PyMouse()
k = PyKeyboard()
Here's an example of clicking the center of the screen and typing "Hello, World!":
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
k.type_string('Hello, World!')
PyKeyboard allows for a range of ways for sending keystrokes:
# pressing a key
k.press_key('H')
# which you then follow with a release of the key
k.release_key('H')
# or you can 'tap' a key which does both
k.tap_key('e')
# note that that tap_key does support a way of repeating keystrokes with a interval time between each
k.tap_key('l',n=2,interval=5)
# and you can send a string if needed too
k.type_string('o World!')
and it supports a wide range of special keys:
#Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)
k.tap_key(k.function_keys[5]) # Tap F5
k.tap_key(k.numpad_keys['Home']) # Tap 'Home' on the numpad
k.tap_key(k.numpad_keys[5], n=3) # Tap 5 on the numpad, thrice
Note you can also send multiple keystrokes together (e.g. when accessing a keyboard shortcut) using the press_keys method:
# Mac example
k.press_keys(['Command','shift','3'])
# Windows example
k.press_keys([k.windows_l_key,'d'])
Consistency between platforms is a big challenge; Please look at the source for the operating system that you are using to help understand the format of the keys that you would need to send. For example:
# Windows
k.tap_key(k.alt_key)
# Mac
k.tap_key('Alternate')
I'd like to make a special note about using PyMouseEvent and PyKeyboardEvent. These objects are a framework for listening for mouse and keyboard input; they don't do anything besides listen until you subclass them. I'm still formalizing PyKeyboardEvent, so here's an example of subclassing PyMouseEvent:
from pymouse import PyMouseEvent
def fibo():
a = 0
yield a
b = 1
yield b
while True:
a, b = b, a+b
yield b
class Clickonacci(PyMouseEvent):
def __init__(self):
PyMouseEvent.__init__(self)
self.fibo = fibo()
def click(self, x, y, button, press):
'''Print Fibonacci numbers when the left click is pressed.'''
if button == 1:
if press:
print(self.fibo.next())
else: # Exit if any other mouse button used
self.stop()
C = Clickonacci()
C.run()
Intended Functionality of Capturing in PyUserInput
For PyMouseEvent classes, the variables "capture" and "capture_move" may be
passed during instantiation. If capture=True
is passed, the intended result
is that all mouse button input will go to your program and nowhere else. The
same is true for capture_move=True
except it deals with mouse pointer motion
instead of the buttons. Both may be set simultaneously, and serve to prevent
events from propagating further. If you notice any bugs with this behavior,
please bring it to our attention.
A Short Todo List
These are a few things I am considering for future development in PyUserInput:
- Ensuring that PyMouse capturing works for all platforms
- Implement PyKeyboard capturing (add PyKeyboardEvent for Mac as well)
- PyMouse dynamic delta scrolling (available in Mac and Windows, hard to standardize)
- Make friends with more Mac developers, testing help is needed...
Many thanks to
Pepijn de Vos - For making PyMouse and allowing me to modify and distribute it along with PyKeyboard.
Jack Grigg - For contributions to cross-platform scrolling in PyMouse.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot