【问题标题】:Python Multithreading with pynput.keyboard.listenerPython 多线程与 pynput.keyboard.listener
【发布时间】:2020-03-31 04:40:40
【问题描述】:

我正在建造一辆自动驾驶遥控车。汽车由一个树莓派(客户端)控制,它将图像数据发送到我的计算机(服务器),计算机处理图像帧并对汽车做出响应(全部使用 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 循环和键盘侦听器应该并行运行,但我不确定它们为什么不并行运行。使用此配置,按键被跟踪,但服务器/客户端交互永远不会开始。我已尝试重新格式化代码,但似乎无法让操作并行发生。

如果有更简单或资源消耗更少的方法来做到这一点,我愿意接受新的想法。这对我来说是最有意义的。我真的只是希望代码尽可能干净。

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

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

【问题讨论】:

    标签: python-3.x linux multithreading opencv pynput


    【解决方案1】:

    不要使用with 语句来初始化你的监听器尝试:

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2015-02-11
      • 2013-06-29
      • 1970-01-01
      相关资源
      最近更新 更多