4

我使用 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)
4

1 回答 1

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_socketpressrelease方法中使用

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给你的pressandrelease方法,你可以试试这个:

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

你准备好了。

于 2021-03-22T16:23:33.260 回答