初始Python的异步IO操作(待完善)

 1 import aiohttp
 2 import asyncio
 3 
 4 def consumer():
 5     r=''
 6     while True:
 7         n = yield r
 8         if n:
 9             r='200 OK'
10             print('客户取走了%s'%(str(n)))
11         else:
12             print('没货')
13 
14 def producer(c):
15     n=0
16     c.send(None)
17     while n<5:
18         n+=1
19         print('生产了%s'%(str(n)))
20         r = c.send(n)
21         print('用户回复%s'%r)
22 
23 c=consumer()
24 producer(c)
运行结果:

生产了1 客户取走了1 用户回复200 OK 生产了2 客户取走了2 用户回复200 OK 生产了3 客户取走了3 用户回复200 OK 生产了4 客户取走了4 用户回复200 OK 生产了5 客户取走了5 用户回复200 OK

import threading
import asyncio

async def hello():
    print('Hello world! (%s)' % threading.currentThread())
    await asyncio.sleep(1)
    print('Hello again! (%s)' % threading.currentThread())

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

运行结果:

Hello world! (<_MainThread(MainThread, started 2600)>)
Hello world! (<_MainThread(MainThread, started 2600)>)
Hello again! (<_MainThread(MainThread, started 2600)>)
Hello again! (<_MainThread(MainThread, started 2600)>)

备忘:

对于aiohttp中的到的get对象为aiohttp.ClientResponse,通过text()方法可以得到string类型的文本,通过read()可以得到类似于content的二进制内容,通过content.read(n)可以得到大小为n的内容
posted @ 2020-02-09 22:43  莫等闲™  阅读(136)  评论(0)    收藏  举报