1

I wrote a macro that use key-presses to record. It is using the keyboard module that does not work on macOS.

Code

import time
import keyboard
import pyautogui

while True:
    if keyboard.is_pressed('e'):
        #recording
        v = [0]
        z = True
        m = time.time()
        while z == True:
            if keyboard.is_pressed('space'):
                v.append(time.time() - m)
            elif keyboard.is_pressed('e'):
                print("Stopped recording")
                z = False
        print(v)
    elif keyboard.is_pressed('x'):
        #replaying
        pyautogui.click()
        for b in range(len(v)-1):
            time.sleep(v[b + 1] - v[b])
            pyautogui.keyDown('space')
    elif x == "q":
        #if key 'q' is pressed, it stops
        break

I tried to use pynput but without success to detect key presses in the second while loop.

How to modify the code so it can work on mac?

2
  • Support for Mac is marked as experimental. Have you confirmed with the docs that what you are trying to achieve is supposed to work on Mac ? Straight from the docs: ` Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!).` Commented Dec 30, 2022 at 16:53
  • instead of using keyboard, try using pyobjc-framework-Quartz, which is a Python wrapper for the Quartz event-handling framework on Mac Commented Dec 30, 2022 at 16:56

1 Answer 1

1

Welcome to SO!

That cannot work, since a keypress is an asynchronous operation, which cannoct be collected without asynchronous event handlers.

A simple way to obtain what you want is to use pynput.

In a bunch of lines you can achieve what you tried to do:

from pynput import keyboard

recording = False
v = [0]
m = 0

def start_recording():
    recording = True
    m = time.time()

def stop_recording():
    recording = False
    print("Stopped recording")

def on_press(key):
    if key == 'e':
        if recording:
            stop_recording()
        else:
            start_recording()
    elif key == keyboard.Key.space and recording:
        v.append(time.time() - m)

listener = keyboard.Listener(on_press=on_press)
listener.start()
listener.join() # This will prevent main process to end

Same goes for the x case and the q case, which I'll leave to you as an exercise.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.