Home > OS >  Can't check what button is pressed in pynput
Can't check what button is pressed in pynput

Time:10-24

I have problem with Keys in pynput

on_press function should check if button pressed i 'h' but it gives error

from pynput.keyboard import Key, Listener


def on_press(key):
    print(key)
    if key == Key.h:
        print('done')


def on_release(key):
    print('{0} release'.format(key))
    if key == Key.esc:
        return False


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

CodePudding user response:

the error is created by the if key == Key.h: statement inside the on_press function. When i comment this out, it works without error.

So this works:

from pynput.keyboard import Key, Listener


def on_press(key):
    print(key)
    # if key == Key.h:    # <-- cause the error
    #     print('done')  # <-- cause the error


def on_release(key):
    print('{0} release'.format(key))
    if key == Key.esc:
        return False


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

returns (when i press various buttons etc):

'h'
'h' release
Key.alt_l
Key.tab
Key.alt_l release
Key.tab release
Key.alt_l
Key.tab
Key.alt_l release

It looks like the examples use a try-except block for the equivalent on_press function that you have created.

Here is the link to how it works: https://pynput.readthedocs.io/en/latest/keyboard.html

When i replace the function with this is performs well:

def on_press(key):
    print(key)
    try:
        if key == Key.h:
            print('done')
    except:
        print('something else')

and i get this:

'h'
something else
'h' release
'i'
something else
'i' release
Key.alt_l
something else
Key.tab
something else
Key.alt_l release
Key.tab release
Key.alt_l

You can see that the exception needs to be handled (many time) from the above, which is why the code in the question was broken.

CodePudding user response:

your way to solve this problem doesn't work or maybe it's mine misunderstanding. When i tried to comment every print, to only print 'done' after checking if pressed key is 'h' it doesn't work

def on_press(key):
    try:
        if key == Key.h:
            print('done')
    except:
        return


def on_release(key):
    #print('{0} release'.format(key))
    if key == Key.esc:
        return False
  • Related