Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 龙卷风协同程序的问题。不';不能异步运行_Python_Asynchronous_Tornado_Yield_Coroutine - Fatal编程技术网

Python 龙卷风协同程序的问题。不';不能异步运行

Python 龙卷风协同程序的问题。不';不能异步运行,python,asynchronous,tornado,yield,coroutine,Python,Asynchronous,Tornado,Yield,Coroutine,经过几次痛苦的尝试,我写了这样的东西: urls=[ 'http://localhost', 'http://www.baidu.com', 'http://www.taobao.com', 'http://www.163.com', 'http://www.sina.com', 'http://www.qq.com', 'htt

经过几次痛苦的尝试,我写了这样的东西:

urls=[
            'http://localhost',
            'http://www.baidu.com',
            'http://www.taobao.com',
            'http://www.163.com',
            'http://www.sina.com',
            'http://www.qq.com',
            'http://www.jd.com',
            'http://www.amazon.cn',
        ]


@tornado.gen.coroutine
def fetch_with_coroutine(url):

    response=yield tornado.httpclient.AsyncHTTPClient().fetch(url)
    print url,len(response.body)
    raise tornado.gen.Return(response.body)


@tornado.gen.coroutine
def main():
    for url in urls:
        yield fetch_with_coroutine(url)


timestart=time.time()
tornado.ioloop.IOLoop.current().run_sync(main)
print 'async:',time.time()-timestart
但它甚至比同步代码慢一点。此外,输出的顺序总是相同的,因此我认为它不会异步运行。 我的代码出了什么问题?

main()
中,您正在调用
fetch\u with\u corroutine
一次调用一个;您使用
yield
的方式意味着在第一次提取完成之前,第二次提取无法开始。相反,您需要首先启动它们,然后以单一收益率等待它们:

@gen.coroutine
def main():
    # 'fetches' is a list of Future objects.
    fetches = [fetch_with_coroutine(url) for url in urls]
    # 'responses' is a list of those Futures' results
    # (i.e. HTTPResponse objects).
    responses = yield fetches