首页 > 编程语言 > 详细

python【协程】【自带模块asyncio】

时间:2021-09-02 21:59:29      阅读:20      评论:0      收藏:0      [点我收藏+]
  1. 基本使用
# 1. asyncio.sleep
import threading
import asyncio

@asyncio.coroutine
def hello():
    print(‘Hello world! (%s)‘ % threading.currentThread())
    yield from asyncio.sleep(1)
    print(‘Hello again! (%s)‘ % threading.currentThread())

loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()




# 2.  asyncio.open_connection
import asyncio

@asyncio.coroutine
def wget(host):
    print(‘wget %s...‘ % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = ‘GET / HTTP/1.0\r\nHost: %s\r\n\r\n‘ % host
    writer.write(header.encode(‘utf-8‘))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b‘\r\n‘:
            break
        print(‘%s header > %s‘ % (host, line.decode(‘utf-8‘).rstrip()))
    # Ignore the body, close the socket
    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()
  1. 【async和await】
import asyncio

@asyncio.coroutine
def hello():
    print("Hello world!")
    r = yield from asyncio.sleep(1)
    print("Hello again!")


用新语法重新编写如下:
import asyncio

async def hello():
    print("Hello world!")
    r = await asyncio.sleep(1)
    print("Hello again!")

python【协程】【自带模块asyncio】

原文:https://www.cnblogs.com/amize/p/15219956.html

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