我第一次尝试gevent,并遇到了一些困难。我敢肯定可能有一个简单的方法,但是我似乎找不到答案。所以这就是困扰我的地方:
这是来自here的gevent的示例:
import gevent
import signal
def run_forever():
gevent.sleep(1000)
if __name__ == '__main__':
gevent.signal(signal.SIGQUIT, gevent.kill)
thread = gevent.spawn(run_forever)
thread.join()
这会产生一个可以永久运行的Greenlet(实际上不是1000秒!),它应该在KeyboardInterrupt上正常关闭程序。现在,当我按Ctrl ^ C时,程序会正常关闭,但问题是它会打印出一些下面不希望看到的迹线:
^CTraceback (most recent call last):
File "test.py", line 14, in <module>
thread.join()
File "src/gevent/greenlet.py", line 711, in gevent._greenlet.Greenlet.join
File "src/gevent/greenlet.py", line 737, in gevent._greenlet.Greenlet.join
File "src/gevent/greenlet.py", line 726, in gevent._greenlet.Greenlet.join
File "src/gevent/_greenlet_primitives.py", line 60, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src/gevent/_greenlet_primitives.py", line 64, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src/gevent/__greenlet_primitives.pxd", line 35, in gevent.__greenlet_primitives._greenlet_switch
KeyboardInterrupt
鉴于here,我尝试了一些小技巧
gevent.get_hub().NOT_ERROR += (KeyboardInterrupt,)
但是不幸的是,它不能解决我的问题。还有其他方法可以处理gevent的这种行为吗?我只希望gevent不要在KeyboardInterrupt上打印堆栈跟踪并优雅地关闭程序。