Stop pyzmq receiver from KeyboardInterrupt

Following this example in ร˜MQ docs, I am trying to create a simple receiver. This example uses an infinite loop. Everything works perfectly. However, on MS Windows, when I press CTRL + C to raise KeyboardInterrupt, the loop does not break. The recv() method seems to somehow ignore the exception. However, I would like to exit the process by pressing CTRL + C rather than killing it. Is it possible?

+4
source share
4 answers

Object A zmq.Poller helps:

 def poll_socket(socket, timetick = 100): poller = zmq.Poller() poller.register(socket, zmq.POLLIN) # wait up to 100msec try: while True: obj = dict(poller.poll(timetick)) if socket in obj and obj[socket] == zmq.POLLIN: yield socket.recv() except KeyboardInterrupt: pass # Escape while loop if there a keyboard interrupt. 

Then you can do things like:

 for message in poll_socket(socket): handle_message(message) 

and the for loop will automatically end on Ctrl-C. It seems that the translation from Ctrl-C to Python KeyboardInterrupt occurs only when the interpreter is active and Python has not given control to the low-level C code; the pyzmq recv() call seems to block when using low-level C code, so Python will never get the opportunity to release KeyboardInterrupt. But if you use zmq.Poller , it will stop with a timeout and give the interpreter a chance to release KeyboardInterrupt after the timeout has ended.

+2
source

In response to @Cyclone's request, I propose the following as a possible solution:

 import signal signal.signal(signal.SIGINT, signal.SIG_DFL); # any pyzmq-related code, such as `reply = socket.recv()` 
+4
source

I don't know if this will work on Windows, but on Linux I did something like this:

 if signal.signal(signal.SIGINT, signal.SIG_DFL): sys.exit() 
+2
source

Try ctrl + break (as in the key above the Up page, I had to look for it, I donโ€™t think I have ever touched this key before) the stream suggested at the bottom. I did not do anything unusual, but it seems to work well in cases where I tried.

+1
source

Source: https://habr.com/ru/post/1486870/


All Articles