Search code examples
pythonpython-2.7tornado

Need help on tornado coroutines


I'm new to python and tornado. I was trying some stuff with coroutines.

def doStuff(callback):
    def task():
        callback("One Second Later")
    Timer(1,task).start()

@gen.coroutine
def routine1():    
    ans = yield gen.Task(doStuff)
    raise gen.Return(ans)

if __name__ == "__main__":
    print routine1()

I'm trying to get the result of doStuff() function, which I expect to be "One Second Later". But it's not working. Any help would be appreciated. Thank you


Solution

  • What's probably happening is, you haven't started the IOLoop, nor are you waiting for your coroutine to complete before your script exits. You'll probably notice your script runs in a couple milliseconds, rather than pausing for a second as it ought. Do this:

    if __name__ == "__main__":
        from tornado.ioloop import IOLoop
        print IOLoop.instance().run_sync(routine1)