Kittenmittons
Kittenmittons

Reputation: 418

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

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.

Upvotes: 1

Views: 1323

Answers (1)

Benjamin James Drury
Benjamin James Drury

Reputation: 2383

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.

Upvotes: 1

Related Questions