0

I want to write a program which counts, how often a key is pressed on my keyboard (e.g. per day). I can use Pynput to recognize a certain keypress, but I'm struggling with the counting part. Here's what I got so far:

from pynput.keyboard import Key, Listener
i = 0
def on_press(key, pressed):
    print('{0} pressed'.format(
        key))
    if pressed({0}):
        i = i + 1
        
def on_release(key):
    if key == Key.esc: 
        # Stop listener
        return False

# Collect events until released 
with Listener( 
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

That executes the following error: TypeError: on_press() missing 1 required positional argument: 'pressed'

I also don't know how to seperate all 26 letters and am not really sure what to do now...does anyone have an idea?

  • Looks like `on_press` function only takes in one argument. [Docs](https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard) – Ieshaan Saxena Aug 31 '20 at 12:22

2 Answers2

1

I'm trying to figure this exact problem out myself. To answer what the error wants, it wants you to define the parameter "pressed" in your arguments passed to on_press.

ex.

    def on_press(key, pressed=0):
        print('{0} pressed'.format(
            key))
        if pressed({0}):
            i = i + 1

your i = 0 above that block is out of scope for the on_press block, and therefore cannot be used.

The problem I'm having is, I can get it to count the keystrokes recursively, however it doesn't stop and goes to the max recursion depth with just one keystroke!

I'll reply again if I make any progress. Good luck to you as well!

--- I figured it out! --- The following link to another StackOverflow post led me in the right direction: Checking a specific key with pynput in Python

Here's my code. It will display the character typed and increment the count of keys typed:

    from pynput.keyboard import Key, Listener

    strokes = 0


    def on_press(key):
        if key == Key.esc:
            return False
        print('{0} pressed'.format(
            key))
        global strokes
        strokes += 1
        print(strokes)


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

I hope this helps!

Excelsiur
  • 41
  • 3
0
from pynput import keyboard

c=0
with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.esc:
            break
        elif (str(event)) == "Press(key='1')":
                c+=1
                print(c)        

You can use any keys inside "Press(key='1')" like "Press(key='2')" , "Press(key='q')"

Anand
  • 1
  • 1