Cua*_*due 13 python asynchronous tornado
我写了一个程序,它有一个定期从主要调用的协程,ioloop如下所示:
from tornado import ioloop, web, gen, log
tornado.log.enable_pretty_printing()
import logging; logging.basicConfig()
@gen.coroutine
def callback():
print 'get ready for an error...'
raise Exception()
result = yield gen.Task(my_async_func)
l = ioloop.IOLoop.instance()
cb = ioloop.PeriodicCallback(callback, 1000, io_loop=l)
cb.start
l.start()
Run Code Online (Sandbox Code Playgroud)
我得到的输出很简单:
$ python2 app.py
get ready for an error...
get ready for an error...
get ready for an error...
get ready for an error...
Run Code Online (Sandbox Code Playgroud)
这raise Exception()是默默无视的!如果我将回调改为公正
def callback():
print 'get ready for an error...'
raise Exception()
Run Code Online (Sandbox Code Playgroud)
我得到了完整的堆栈跟踪,就像我期望的那样(并且需要).如何在使用协程时获得堆栈跟踪?
@tornado.gen.coroutine使函数返回tornado.concurrent.Future对象,所以你不必将其包装,tornado.gen.Task但你可以使用yield关键字调用它:
@tornado.gen.coroutine
def inner():
logging.info('inner')
@tornado.gen.coroutine
def outer():
logging.info('outer')
yield inner()
Run Code Online (Sandbox Code Playgroud)
以这种方式修饰的函数中的异常被包装到此tornado.concurrent.Future对象中,稍后可以使用其exception()方法返回它.在你的情况下tornado.ioloop.PeriodicCallback调用你的回调方法,之后它只是抛弃返回的tornado.concurrent.Future对象以及它包含的异常.要检测异常,您可以使用链调用:
@tornado.gen.coroutine
def inner():
raise Exception()
@tornado.gen.coroutine
def outer():
try:
yield inner()
except Exception, e:
logging.exception(e)
Run Code Online (Sandbox Code Playgroud)
但是在你的情况下,只是在投掷之后抓住它更容易:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.gen
import tornado.ioloop
import tornado.options
import logging
tornado.options.parse_command_line()
@tornado.gen.coroutine
def callback():
logging.info('get ready for an error...')
try:
raise Exception()
except Exception, e:
logging.exception(e)
main_loop = tornado.ioloop.IOLoop.instance()
scheduler = tornado.ioloop.PeriodicCallback(callback, 1000, io_loop = main_loop)
scheduler.start()
main_loop.start()
Run Code Online (Sandbox Code Playgroud)
@gen.engine不会使函数返回a,tornado.concurrent.Future因此异常不会被包装.