Python Forum

Full Version: Writing to Excel file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have written a simple program that captures keystroke data. I created two functions (on_Press and on_release), I want to write all captured keystrokes data from on_press() & on_release() to a separate excel file every time the enter key is pressed or code executed.

But after executing below code, the program is only writing the "Enter" key data and ignoring the rest.

Any ideas, please?

Thanks

from pynput.keyboard import Key, Listener
from datetime import datetime
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile



key_pressed = [0]
key_press_time = [0]
key_released = [0]
key_release_time = [0]


def on_press(key):
    global key_pressed, key_press_time, key_released, key_release_time
    key_pressed = key
    key_press_time = datetime.utcnow().strftime('%M:%S.%f')

    return key_pressed, key_press_time


def on_release(key):
    global key_pressed, key_press_time, key_released, key_release_time
    key_released = key
    key_release_time = datetime.utcnow().strftime('%M:%S.%f')

    key_dict = {'Key_Pressed':[key_pressed],
                'Key_Press_Time':[key_press_time],
                'Key_Released':[key_released],
                'Key_Release_Time':[key_release_time]}

    kd = pd.DataFrame(key_dict)

    print(kd)


    if key == Key.enter:
        writer = ExcelWriter('KeystrokeData.xlsx')
        kd.to_excel(writer,'Sheet1',index=False)
        writer.save()
        # Stop listener
        return False




# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
The listener is capturing all of the keystrokes which is what you need if you want to capture 'Enter' key.
(I can see it happening when I run your code)

But these are interrupts, and all keys are going to be serviced immediately, no matter what you are doing,
possibly when writing to ExcelWriter (unless interrupts are disabled during the write).
I think this task is up to you, and you need to turn the listener off during this time.
Thank you for the response. I will try turning the listener off and see if it works

Regards