Python 多线程 pynput.keyboard.listener

Python Multithreading with pynput.keyboard.listener

我正在建造一辆自动驾驶遥控车。汽车由 raspberry pi(客户端)控制,它向我的计算机(服务器)发送图像数据,计算机处理图像帧并向汽车做出响应(全部使用 python 套接字) .这非常有效。我现在正在尝试向 python 添加一个关键侦听器,这样我就可以在所有套接字交互发生时手动控制汽车。我想使用多线程来这样做。以下是我认为它应该如何工作:

import cv2
from pynput import keyboard
from Server import Server

###Keyboard Listener###
def keyPress(key): #send keypress to client
    server.sendCommand((str(key)))
with keyboard.Listener(on_press=keyPress) as listener: #new listener thread
    listener.join() #activate thread

###Server/ client interaction###
host, port = '10.78.1.195', 8000  # home
server = Server(host, port) #server object
server.connect() #connect
while server.isOpened(): #do while the server is open
    frame = server.getStreamImage() #get an image from the client each frame
    server.sendCommand("0") #send a command to the server (arbituary for now, but will be a neural network ouotput
    cv2.imshow("t", frame)  # show image
    # cv2.imshow("tttttt", nnInput)  # show image CONFIGURE PERSPECTIVE TRANSFORM AFTER CAMERA MOUNT
    if cv2.waitKey(1) == ord('q'): #quit if q pressed
        server.sendCommand('q')  # tell client to close
        server.close()  # break if 'q' pressed
cv2.destroyAllWindows() #close opencv windows

如果您想要任何客户端或服务器代码,我很乐意展示它。我没有包含它,因为它运行良好。

所以,在我看来,while 循环和键盘侦听器应该并行运行,但我不确定为什么它们不是。使用此配置,按键会被跟踪,但 server/client 交互永远不会开始。我已尝试重新格式化代码,但似乎无法让操作并行发生。

如果有更简单或资源占用更少的方法来执行此操作,我乐于接受新想法。这对我来说是最有意义的。我真的只是希望代码尽可能干净。

我的 python 版本是 3.7。我是 运行 Ubuntu 19.10。 pynput 是版本 1.4.5.

如果我可以提供任何其他信息,请询问。非常感谢!

不要使用 with 语句来初始化您的侦听器,请尝试:

listener = keyboard.Listener(on_press=keyPress)
listener.start()

with 语句阻塞了主线程。 使用 start 而不是 with / join 你创建一个非阻塞线程允许主循环开始。