python中event key_python gevent: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 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?

解决方案

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:

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值