如何使用键盘中断 Python 中的 recvfrom() 调用? [英] How can I interrupt a recvfrom() call in Python with keyboard?

查看:43
本文介绍了如何使用键盘中断 Python 中的 recvfrom() 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序的 main() 函数中运行了一个循环,如下所示

I have a loop running in the main() function of my program that looks as follows

while True:
    data, addr = sock.recvfrom(MAX_MESS_LEN)
    thread.start_new_thread(message_handler, (data, addr,))

我想介绍一些功能,让我可以点击q"来跳出循环并结束程序.我不确定如何执行此操作,因为程序会等待 recvfrom() 调用,直到收到消息.有没有办法实现中断键或键盘事件捕获器之类的?现在我使用 ctrl-c 来键盘中断程序,但这似乎有点草率.

I would like to introduce functionality that allows me to perhaps hit 'q' to break out of the loop and end the program. I'm not sure how to do this since the program waits on the recvfrom() call until receiving a message. Is there a way to implement an interrupt key or keyboard event catcher or something? Right now I use ctrl-c to keyboard interrupt the program but that seems a bit sloppy.

推荐答案

您可以先尝试检查套接字中是否有任何数据,然后再尝试从套接字接收数据?

You could try checking to see if there is any data in the socket before you attempts to receive from it in the first place?

dataInSocket, _, _ = socket.select.select([sock], [], [])
if dataInSocket:
    data, addr = sock.recvfrom(MAX_MESS_LEN)
    thread.start_new_thread(message_handler, (data, addr,))

我在这里有点猜到你的代码,所以这段代码可能不会干净地复制和粘贴到你的代码中.您需要使其适用于您自己的程序.

I've kind of guessed at your code a bit here, so this code probably won't copy and paste into yours cleanly. You'll need to make it work for your own program.

这篇关于如何使用键盘中断 Python 中的 recvfrom() 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆