How can I interrupt a recvfrom() call in Python with keyboard?

久未见 提交于 2021-01-29 04:13:14

问题


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,))

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.


回答1:


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.



来源:https://stackoverflow.com/questions/27177870/how-can-i-interrupt-a-recvfrom-call-in-python-with-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!