Automating Key Presses on Mac OS with Python

Automating Key Presses on Mac OS with Python

Welcome to a quick guide on how to automate key presses on your Mac using Python. This script is designed to press the space bar continuously at a very short interval, but can be adapted for other keys or uses.
What Does the Script Do?

  • Functionality: It presses the space bar every 0.01 seconds (adjustable).
  • Control: You can toggle the auto-press feature on/off by pressing Shift + Middle Mouse Button.

How to Use This ScriptInstallation and Running

  1. Permissions: Ensure your terminal app has Accessibility permissions. Go to System Preferences > Security & Privacy > Privacy > Accessibility, and check your terminal app.
  2. Running the Script:
    • Save the script as AutoPress.py.
  3. Usage:
    • Simply press Shift + Middle Mouse Button to start or stop the space bar spamming.

After starting the script, you'll see:

Script started. Press Shift + Middle Mouse Button to toggle auto space pressing. Ensure the target application is in focus.

Execute with sudo for necessary permissions:

sudo python3 AutoPress.py

Navigate to the script's location in the terminal:

cd /path/to/your/script

The Python Script
Here's the script you'll need to create:

import time
from pynput import keyboard, mouse
from threading import Thread, Event

# Initialize flags and events
auto_press_enabled = False
stop_event = Event()
shift_pressed = False

# Create a controller object for the keyboard
keyboard_controller = keyboard.Controller()

def press_space():
    """Press the space bar at specified intervals when enabled."""
    global auto_press_enabled
    interval = 0.01  # 10 milliseconds
    while not stop_event.is_set():
        if auto_press_enabled:
            try:
                keyboard_controller.press(keyboard.Key.space)
                keyboard_controller.release(keyboard.Key.space)
                # Uncomment for debugging (may slow down the loop)
                # print("Space pressed")
            except Exception as e:
                print(f"Error pressing space: {e}")
            time.sleep(interval)
        else:
            stop_event.wait(0.1)  # Wait before checking again

def toggle_auto_press():
    """Toggle the space auto press functionality."""
    global auto_press_enabled
    auto_press_enabled = not auto_press_enabled
    status = "enabled" if auto_press_enabled else "disabled"
    print(f"Auto press {status}.")

def on_mouse_click(x, y, button, pressed):
    """Toggle auto press when Shift + Middle Mouse Button is clicked."""
    global shift_pressed
    if button == mouse.Button.middle and pressed:
        if shift_pressed:
            toggle_auto_press()

def on_key_press(key):
    """Monitor Shift key state."""
    global shift_pressed
    if key == keyboard.Key.shift:
        shift_pressed = True
        print("Shift key pressed.")

def on_key_release(key):
    """Monitor Shift key state."""
    global shift_pressed
    if key == keyboard.Key.shift:
        shift_pressed = False
        print("Shift key released.")

def start_listeners():
    """Start the keyboard and mouse listeners."""
    with mouse.Listener(on_click=on_mouse_click) as mouse_listener, \
         keyboard.Listener(on_press=on_key_press, on_release=on_key_release) as keyboard_listener:
        mouse_listener.join()
        keyboard_listener.join()

if __name__ == '__main__':
    # Start the space pressing function in a separate thread
    thread = Thread(target=press_space, daemon=True)
    thread.start()

    print("Script started.")
    print("Press Shift + Middle Mouse Button to toggle auto space pressing.")
    print("Ensure the target application is in focus.")

    # Start listening for mouse and keyboard events
    start_listeners()

FAQs

  • The script doesn't run? Make sure you've granted Accessibility permissions in System Preferences.
  • How to modify the key or interval? Adjust the keyboard.Key.space to another key or change the interval in the press_space function.

Check Out More on GitHubFor more scripts and automation tools, visit the repository at GitHub - MuckyRat/AutoPressMacOS.
This script provides a foundation for automating repetitive tasks or testing user interfaces with minimal setup. Enjoy automating!