I'm trying to make a code that tracks key presses and mouse clicks

72 Views Asked by At

I have written a code that tries to track key presses and mouse clicks, but there is a problem that the code does not stop when I press ender key, and the code does not write the inputs into an excel file. Asking ChatGPT does not help, it is out of ideas. Please help. Code following below:

import time
import openpyxl
from pynput.mouse import Listener as MouseListener
from pynput.keyboard import Listener as KeyboardListener
from pynput.keyboard import Key

workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = "InputData"
worksheet.append(["Time", "Event Type", "X", "Y", "Button/Key"])

input_count = 0
start_time = time.time()
is_running = True

def stop_listening():
    global is_running
    is_running = False

def record_input(event_type, x, y, action):
    global input_count
    input_count += 1
    current_time = time.time()
    worksheet.append([current_time, event_type, x, y, action])

def on_mouse_click(x, y, button, pressed):
    if pressed:
        event_type = "Mouse Click"
        action = f"Mouse {button} Pressed"
        record_input(event_type, x, y, action)
        print(f"Mouse clicked at ({x}, {y}) with {button}")

def on_key_press(key):
    event_type = "Key Press"
    try:
        action = f"Key Pressed: {key.char}"
        print(f"Key pressed: {key.char}")
        if key == Key.f12:  # Use the F12 key to stop
            print("The F12 key was pressed.")
            stop_listening()
    except AttributeError:
        action = f"Special Key Pressed: {key}"
        print(f"Special key pressed: {key}")
    record_input(event_type, None, None, action)

with MouseListener(on_click=on_mouse_click) as mouse_listener, KeyboardListener(on_press=on_key_press) as keyboard_listener:
    mouse_listener.join()
    keyboard_listener.join()

end_time = time.time()
time_elapsed = end_time - start_time
input_rate = input_count / time_elapsed
workbook.save("InputData.xlsx")
print("Program has finished running.")

I have tried changing my IDE from PyCharm to PyScripter, and ran the code in command prompt. I have tried changing ender key from "-" to "space" to "F12". Nothing helped.

1

There are 1 best solutions below

0
On

Listeners are instances of subclasses of Thread. Since you want to stop listening to key presses and mouse clicks only when a specific key is pressed, you should .join() only the keyboard listener. Joining a thread makes us wait until it terminates.

Here what it could look like:

import time
import openpyxl
from pynput.mouse import Listener as MouseListener
from pynput.keyboard import Listener as KeyboardListener
from pynput.keyboard import Key

workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = "InputData"
worksheet.append(["Time", "Event Type", "X", "Y", "Button/Key"])

def record_input(event_type, x, y, action):
    current_time = time.time()
    worksheet.append([current_time, event_type, x, y, action])

def on_mouse_click(x, y, button, pressed):
    if pressed:
        event_type = "Mouse Click"
        action = f"Mouse {button} Pressed"
        record_input(event_type, x, y, action)
        print(f"Mouse clicked at ({x}, {y}) with {button}")

def on_key_press(key):
    event_type = "Key Press"
    try:
        action = f"Key Pressed: {key.char}"
        print(f"Key pressed: {key.char}")
    except AttributeError:
        action = f"Special Key Pressed: {key}"
        print(f"Special key pressed: {key}")
    
    record_input(event_type, None, None, action)
    
    if key == Key.f12:  # Use the F12 key to stop
        print("The F12 key was pressed.")
        workbook.save("InputData.xlsx")
        print("Program has finished running.")
        return False

with MouseListener(on_click=on_mouse_click) as mouse_listener, KeyboardListener(on_press=on_key_press) as keyboard_listener:
    keyboard_listener.join()

What do you think of this solution?