python gevent: unexpected output in KeyboardInterrupt

一个人想着一个人 提交于 2019-12-10 17:33:37

问题


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 a Ctrl-C, give me this output:

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

Why?
It seems someone is writing the exit time on output.
How can I prevent that KeyboardInterrupt in the first line and the date in the second?


回答1:


Those messages are printed by the gevent Hub, which is intercepting the KeyboardInterrupt being raised. Usually you would see a traceback instead of just KeyboardInterrupt and the current date, but because the Hub is special, you get that output.

You have two ways to solve this issue:

  1. Mark KeyboardInterrupt as a non-error:

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

    With this trick, the Hub won't print any line when KeyboardInterrupt is caught. This might seem a hack, but it's a short and effective way to stop output pollution.

  2. 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 your cleanup code.

    It is important that you exit with an exception from your handler function, otherwise your call to gevent.wait() won't be stopped. The only two exceptions that you can use are SystemExit and GreenletExit (those are the two default exceptions in the NOT_ERROR list above): any other exception will cause gevent to print something on standard error.



来源:https://stackoverflow.com/questions/45556949/python-gevent-unexpected-output-in-keyboardinterrupt

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