Python gevent: unexpected output in KeyboardInterrupt

Running this code

import gevent

def f():
    while True:
        gevent.sleep(1)

if __name__ == '__main__':
    tasks = (gevent.spawn(f),)
    try:
        gevent.wait(tasks)
    except KeyboardInterrupt:
        print("KeyboardInterrupt trapped")

      

and then pressing Ctrl-C give me this output:

$ python receiver.py 
^CKeyboardInterrupt
Tue Aug  8 00:56:04 2017
KeyboardInterrupt trapped

      

Why?
It seems like someone is writing the exit time at the exit.
How can I prevent KeyboardInterrupt

in the first line and in the date in the second?

+3


source to share


1 answer


These messages are printed by gevent Hubs that intercept the raised KeyboardInterrupt. You usually see a traceback instead of a simple KeyboardInterrupt and current date, but since the Hub is special, you get this output.

You have two ways to solve this problem:



  • Mark KeyboardInterrupt as error:

    gevent.get_hub().NOT_ERROR += (KeyboardInterrupt,)
    
          

    With this trick, the hub will not print any lines when it captures KeyboardInterrupt. This may sound like a hack, but it is a short and effective way to stop exit pollution.

  • Register a signal handler for SIGINT:

    def handler(signum, frame):
        print('SIGINT trapped')
        sys.exit(0)
    
    signal.signal(signal.SIGINT, handler)
    
          

    The default signal handler for SIGINT will raise KeyboardInterrupt, but if you define your own signal handler, you can prevent it and run the cleanup code.

    It is important that you exit the exception from the handler function, otherwise your call gevent.wait()

    will not stop. The only two exceptions you can use are SystemExit and GreenletExit (these are the two default exceptions in the above list NOT_ERROR

    ): any other exception will cause gevent to print something on standard error.

+1


source







All Articles