问题
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