Soares
Soares

Reputation: 25

Increment variable in python while printing in file

Hi guys so i have this short piece of code where while the program is running I'm priting every key that I press on my keyboard in a file, one per line. The thing is that i would like that each line has an ID, and that ID has, obviously, to be diferent everytime and i thought that the easier way was to to make this id to be an int that increments after every write operation; but i just can't get it to work, it always print the same int.

# detect key press
def on_press(key, myint=0):
    try:
        f = open("logger.txt", "a")
        upper = str(key.char).upper()
        f.write('{' + '"KeyPressed"' + ':' + '"' + upper + '","_id":"' + str(myint) + '"},' '\n')
        myint += 1
        f.close()
...

with keyboard.Listener(
        on_press=on_press) as listener:
    listener.join()

In this case if I run the program and press: A S D the output is:

{"KeyPressed":"A","_id":"0"},
{"KeyPressed":"S","_id":"0"},
{"KeyPressed":"D","_id":"0"},

Is it possible to achieve my goal?

Upvotes: 0

Views: 420

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

The problem is that every time on_press is called, it gets a new copy of myint, as opposed to using a persistent copy that changes.

You can fix it with a simple closure that saves the state in a parent function:

def get_on_press(myint=0):
    def on_press(key):
        nonlocal myint
        print("on_press:  key: {}  myint: {}".format(key, myint))
        myint += 1
    return on_press

on_press = get_on_press()

You can then call on_press normally:

>>> on_press("a")
on_press:  key: a  myint: 0
>>> on_press("b")
on_press:  key: b  myint: 1
>>> on_press("c")
on_press:  key: c  myint: 2
>>> 

Upvotes: 2

Related Questions