Search code examples
pythontimerkeyloggerpynput

Record momentum consecutively when each key is pressed in a count timer while executing keylogger.py


I have the following code-file keylogger.py below to detect a specific key being pressed and saving to log.txt file. I want to add to this python code a timer that starts when the code starts to run, I also want this part of the code to save the exact moment the keys were pressed starting with the start of the file and save this information in the log.txt file or another separate file (would need to use with open and f.write I think). Several timekeeping ideas I found in How to create a timer on python and https://pythonhow.com/measure-execution-time-python-code/.

So my log.txt would be something like

log.py

RLLR     #this line would already be produced by keylogger.py

R: 0.2s
L:0.24s
L:1.34s
R:2.5s

keylogger.py

from pynput.keyboard import Listener, Key

#set log file location
logFile = "/home/diego/log.txt"



def writeLog(key):
    translate_keys = {
        Key.right: "R",
        Key.left: "L",
    }
    if key in translate_keys:
        with open(logFile, "a") as f:
            f.write(translate_keys[key])

with Listener(on_press=writeLog) as l:
    l.join()

Solution

  • Using separate files would be the simplest solution I think:

    from pynput.keyboard import Listener, Key
    import time
    
    #set log file location for keys pressed
    keysLogFile = "/home/diego/keys_log.txt"
    
    #set log file location for keys timestamps
    timestampsLogFile = "/home/diego/ts_log.txt"
    
    #store start timestamp
    startTime = time.time()
    
    
    def writeLog(key):
        translate_keys = {
            Key.right: "R",
            Key.left: "L",
        }
        if key in translate_keys:
            currentTime = time.time() - startTime
            with open(keysLogFile, "a") as f:
                f.write(translate_keys[key])
            with open(timestampsLogFile, "a") as f:
                f.write(translate_keys[key] + ": " + str(currentTime) + "s\n")
    
    with Listener(on_press=writeLog) as l:
        l.join()
    

    This would give you two separate files:

    keys_log.txt

    RLLR
    

    ts_log.txt

    R: 0.2s
    L: 0.24s
    L: 1.34s
    R: 2.5s