python gevent:KeyboardInterrupt中的意外输出 [英] python gevent: unexpected output in KeyboardInterrupt

查看:173
本文介绍了python gevent:KeyboardInterrupt中的意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码

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")

然后按Ctrl-C,向我显示以下输出:

and then pressing a Ctrl-C, give me this output:

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

为什么?
似乎有人在写输出的退出时间.
如何防止第一行中的KeyboardInterrupt和第二行中的日期?

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?

推荐答案

这些消息由

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. 将KeyboardInterrupt标记为非错误:

  1. Mark KeyboardInterrupt as a non-error:

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

使用此技巧,当捕获KeyboardInterrupt时,集线器将不会打印任何行.这看似很hack,但这是阻止输出污染的一种简短而有效的方法.

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.

为SIGINT注册信号处理程序:

Register a signal handler for SIGINT:

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

signal.signal(signal.SIGINT, handler)

SIGINT的默认信号处理程序将引发KeyboardInterrupt,但如果您定义自己的信号处理程序,则可以阻止它并运行清除代码.

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.

重要的是,您必须从处理程序函数中异常退出,否则不会停止对gevent.wait()的调用.只能使用的两个异常是SystemExit和GreenletExit(这是上面NOT_ERROR列表中的两个默认异常):任何其他异常都会导致gevent在标准错误上打印某些内容.

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.

这篇关于python gevent:KeyboardInterrupt中的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆