Skip to content

Instantly share code, notes, and snippets.

@mengzhuo
Created December 30, 2013 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mengzhuo/8178355 to your computer and use it in GitHub Desktop.
Save mengzhuo/8178355 to your computer and use it in GitHub Desktop.
How Tornado gen.Task making Sync into Async function?
from tornado import gen, ioloop
import urllib2
import re
tre = re.compile('\<title\>(?P<title>[^<]+)',re.IGNORECASE)
from pprint import pformat
@gen.coroutine
def sleep_bug(url):
print 'fetch:'+url
r = yield gen.Task(ioloop.IOLoop.current().add_callback)
print "callback "+ str(r)
title = tre.findall(urllib2.urlopen(url).read())[0].decode('utf-8')
print 'got from:'+url
raise gen.Return(title)
@gen.coroutine
def make_sleepy_bug(sec=3):
print "making..."
re = yield [sleep_bug('http://www.baidu.com'),
sleep_bug('http://www.google.com'),
sleep_bug('http://mengzhuo.org')]
raise gen.Return(re)
if __name__ == '__main__':
loop = ioloop.IOLoop.instance()
#print make_sleepy_bug()
print "done...\n"+pformat([unicode(x) for x in loop.run_sync(make_sleepy_bug)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment