将参数传递给Pynput侦听器

时间:2018-10-24 15:32:18

标签: python-2.7 parameter-passing listener event-listener pynput

我正在使用Pynput侦听器来捕获键盘上的按键,但是问题是我需要将参数传递给on_press和on_release函数,而我只是想不通该怎么做。 您可以在代码中看到,我需要传递客户端套接字,以便我可以将按下/释放的键发送给他。

def handle_keyboard_events(self, client_socket):
    keyboard_listener = keyboard.Listener(on_press=self.on_key_press, on_release=self.on_key_release)
    keyboard_listener.start()

def on_key_press(self, key):
    key_press_command = KeyPress(key)
    self.send_message(key_press_command, True, client_socket)

def on_key_release(self, key):
    key_release_command = KeyRelease(key)
    self.send_message(key_release_command, True, client_socket)

1 个答案:

答案 0 :(得分:0)

我看到您正在使用 self,所以您在 class 内。

为什么不在构造函数中使用 self.client_socket = client_socket

# update your constructor with self.client_socket
def __init__(client_socket, **other_args_of_yours):
    
    # use this object variable when you activate key listener
    self.client_socket = client_socket

或在 self.client_socket = client_socket 方法中添加 handle_keyboard_events()

def handle_keyboard_events(self, client_socket):
    
    self.client_socket = client_socket # <----- update
    
    keyboard_listener = keyboard.Listener(
        on_press=self.on_key_press, 
        on_release=self.on_key_release
    )
    keyboard_listener.start()

并在 self.client_socketpress 方法中使用 release

def on_key_press(self, key):
    key_press_command = KeyPress(key)
    self.send_message(key_press_command, True, self.client_socket) # <--- update

def on_key_release(self, key):
    key_release_command = KeyRelease(key)
    self.send_message(key_release_command, True, self.client_socket) # <--- update

如果你真的想将 client_socket 传递给你的 pressrelease 方法,你可以试试这个:

def handle_keyboard_events(self, client_socket):
    # use lambda to pass the client socket
    # with this method, after you get the `key` you can pass additional params to on_press and on_release
    keyboard_listener = keyboard.Listener(
        on_press=lambda key: self.on_key_press(key, client_socket), # <--- client socket passed
        on_release=lambda key: self.on_key_release(key, client_socket) # <--- client socket passed
    )
    keyboard_listener.start()

# add client socket as new arg
def on_key_press(self, key, client_socket):
    key_press_command = KeyPress(key)
    self.send_message(key_press_command, True, client_socket) # from params
    
# add client socket as new arg
def on_key_release(self, key, client_socket):
    key_release_command = KeyRelease(key)
    self.send_message(key_release_command, True, client_socket) # from params

你准备好了。