mamaluigie
mamaluigie

Reputation: 1

pynput keyboard listener function variable pass

I am having an issue of passing the count variable over to the on_press function that is being called for every key press using the pynput listener library. I am confused as to why the variable is not being incremented then output to the screen. It does increment and output on the first iteration but not on the next. I am confused pls help.

from pynput.keyboard import Listener
import string

count = 0 

def on_press(count):
    count += 1
    print(count)

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

Upvotes: 0

Views: 736

Answers (1)

Stephen Mylabathula
Stephen Mylabathula

Reputation: 398

The issue here surrounds the topic of variable scope. The count variable being referenced inside on_press is the count argument being passed into the function (not the global variable count defined outside the function). Integers in Python are passed by copy to function (not by reference). So what's happening in your code is that you are making a copy of the global variable count, passing that into on_press, and then on_press only increments the local copy of count passed in - hence it will always print out 1.

If you want count to be incremented each time on_press is called, you should directly increment the global count variable as follows:

from pynput.keyboard import Listener
import string

count = 0 

def on_press():
    global count
    count += 1
    print(count)

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

Upvotes: 1

Related Questions