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

代码如下:

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
Host: %s
' % host
    writer.write(header.encode('utf-8'))
    await writer.drain()
    while True:
        line = await reader.readline()
        if line == b'
':
            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之前,用

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

  1. @asyncio.coroutine替换为async
  2. yield from替换为await
原文地址:https://www.cnblogs.com/ncuhwxiong/p/8183035.html