How to pass arguments to functions called by hot keys in pynput?

Viewed 48

I want to call functions by pressing hot keys. I want functions to have arguments with values from users. I am using this documentation: Handling the keyboard

Here is a sample of code to illustrate the problem:

from pynput import keyboard

text_1 = 'printing text_1'
def on_activate_p_1( text_1 ):
    print( text_1 )

text_2 = 'printing text_2'
def on_activate_p_2( text_2 ):
    print( text_2 )

with keyboard.GlobalHotKeys({

        'p+1' : on_activate_p_1,
        'p+2' : on_activate_p_2

        }) as h:
    h.join()

When pressing 'p+1', I am getting an error:

TypeError: on_activate_p_1() missing 1 required positional argument: 'text_1'

Question: how to pass arguments to functions used by (global) hot keys?

2 Answers

Not sure if it's the best way, but you just need to return a function somehow. So for your example you can use lambdas.

i.e.:

from pynput import keyboard

text_1 = 'printing text_1'
def on_activate_p_1( text_1 ):
    print( text_1 )

text_2 = 'printing text_2'
def on_activate_p_2( text_2 ):
    print( text_2 )

with keyboard.GlobalHotKeys({

        'p+1' : lambda: on_activate_p_1("WHATYOUWANT"), 
        'p+2' : lambda: on_activate_p_2("WHATYOUWANT")    

        }) as h:
    h.join()    

The lambdas will return the result of the function you wanted, passing the parameter you need.

Lambdas can also receive a parameter if needed, i.e.: lambda x: on_activate_p_2(x)

You could use partial to bind the arguments to the function upfront:

from functools import partial
from pynput import keyboard

text_1 = 'printing text_1'
def on_activate_p_1( text_1 ):
    print( text_1 )

text_2 = 'printing text_2'
def on_activate_p_2( text_2 ):
    print( text_2 )


activateP1 = partial(on_activate_p_1, text_1)
activateP2 = partial(on_activate_p_2, text_2)

with keyboard.GlobalHotKeys({
        'p+1' : activateP1, 
        'p+2' : activateP2    

        }) as h:
    h.join()    
Related