我前段时间开始学习Tornado框架。我已经面对缺乏经验用户的文档,并检查了asyncio模块文档。 所以问题是,我在asyncio中有一些简单的代码:
import asyncio
@asyncio.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield from asyncio.sleep(1.0)
return x + y
@asyncio.coroutine
def print_sum(x, y):
result = yield from compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
然后我尝试使用Tornado框架做同样的事情:
from tornado.ioloop import IOLoop
from tornado import gen
@gen.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield gen.sleep(1.0)
return (x+y)
@gen.coroutine
def print_sum(x, y):
result = yield compute(x, y)
print("%s + %s = %s" % (x, y, result))
IOLoop.instance().run_sync(print_sum(1,2))
但遗憾的是Tornado代码引发了这样的例外:
Compute 1 + 2 ...
Traceback (most recent call last):
File "tornado_coroutine.py", line 19, in <module>
IOLoop.instance().run_sync(print_sum(1, 2))
File "C:\Python34\lib\site-packages\tornado\ioloop.py", line 421, in run_sync
return future_cell[0].result()
File "C:\Python34\lib\site-packages\tornado\concurrent.py", line 209, in resul
t
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "C:\Python34\lib\site-packages\tornado\ioloop.py", line 402, in run
result = func()
TypeError: 'Future' object is not callable
也许IOLoop试图创造一个新的&#34;圈&#34;在所有协同程序都返回了它们的值之后?
答案 0 :(得分:19)
run_sync
将一个函数(或其他&#34;可调用的&#34;)作为参数。您正在调用该函数,然后将结果作为参数。您只需使用lambda
:
IOLoop.instance().run_sync(lambda: print_sum(1,2))