首页 > Web开发 > 详细

用asyncio的异步网络连接来获取sina、sohu和163的网站首页

时间:2018-01-03 13:38:51      阅读:567      评论:0      收藏:0      [点我收藏+]

代码如下:

import asyncio

async def wget(host):
    print(‘wget %s...‘ % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = await connect
    header = ‘GET / HTTP/1.0\r\nHost: %s\r\n‘ % host
    writer.write(header.encode(‘utf-8‘))
    await writer.drain()
    while True:
        line = await reader.readline()
        if line == b‘\r\n‘:
            break
        print(‘%s header > %s‘ % (host, line.decode(‘utf-8‘).rstrip()))

        writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in [‘www.sina.com.cn‘, ‘www.sohu.com‘, ‘www.163.com‘]]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

上面的写法只适用与python 3.5及其之后的版本,再python 3.5之前,用

请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:

  1. 把@asyncio.coroutine替换为async;
  2. 把yield from替换为await。

用asyncio的异步网络连接来获取sina、sohu和163的网站首页

原文:https://www.cnblogs.com/ncuhwxiong/p/8183035.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!