Why am I getting None
in keystrokes.txt instead of the key names in python?
import keyboard
log_file = 'keystrokes.txt'
def on_key_press(event):
with open(log_file, 'a') as f:
f.write('{}\n'.format(event.name))
keyboard.on_press(on_key_press)
keyboard.wait()
This might have to do with me being on macOS. Even though I did add sudo
to the process to give it admin privileges.
I don't think keyboard has ever worked reliably on macOS.
A more modern module that seems to work reliably with Python 3.12.1 and macOS 14.2.1 is pynput
Here's a brief example of how you could capture keyboard activity using the pynput module.
pip install pynput
Press esc to end the program.
from pynput import keyboard
def press(key):
if hasattr(key, "char"):
with open("key.log", "a") as log:
log.write(key.char)
def release(key):
return key != keyboard.Key.esc
with keyboard.Listener(on_press=press, on_release=release) as listener:
listener.join()