Search code examples
pythonconcatenationpynput

Python script fails when trying to concatenate


So I'm trying to make a keylogger as a little starter project to help me learn more about programming. I am using pynput to detect keyboard input and I want to keep adding the characters to a variable called line. The script I am about to show works when I put line += str2 outside the function, but not in (The str variables were put there to debug this exact thing.)

Here is the code:

import msvcrt, datetime
from pynput.keyboard import Key, Listener

date = str(datetime.date.today())
line = "a"
str1 = "1"
str2 = "2"

#Saves given data to a dated text file.
def saveToFile(data):
    file = open("keylog_{}.txt" .format(date), "a+")
    file.write(str(data))
    file.close()

def on_press(key):
    line += str2
    print(line)

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

Thanks in advance for anyone who can help me figure out why this happens.


Solution

  • This has to do with variable scope. line in your on_press method is not the same variable as line up above. If you want to do something like that, you need to tell it to use the global scope variable:

    def on_press(key):
        global line
        line += key
        print(line)